Skip to content

Instantly share code, notes, and snippets.

@gianpaj
Created June 8, 2018 14:20
Show Gist options
  • Save gianpaj/e7b4c7c3cdc158e3552449a3577453ff to your computer and use it in GitHub Desktop.
Save gianpaj/e7b4c7c3cdc158e3552449a3577453ff to your computer and use it in GitHub Desktop.
/**
Instructions:
npm init
npm install cors express multer
node node-js-uploader-and-serve.js
OR
nodemon node-js-uploader-and-serve.js
tested on:
Node v10.3.0
├── [email protected]
├── [email protected]
├── [email protected]
*/
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const cors = require('cors');
const path = require('path');
const UPLOAD_PATH = 'uploads/';
const upload = multer({ dest: UPLOAD_PATH });
const app = express();
app.use(cors());
app.post('/photos/upload', upload.array('file', 6), function (req, res) {
// req.files is array of `photos` files
console.log(req.files);
// req.body will contain the text fields, if there were any
console.log(req.body);
res.json({ data: req.files });
})
app.get('/photos/:id', async (req, res, next) => {
fs.readFile(UPLOAD_PATH + req.params.id, function(err, data) {
if (err) {
res.send("Oops! Couldn't find that id.");
} else {
// set the content type based on the file
res.contentType(req.params.id);
res.send(data);
}
res.end();
});
})
app.listen(7000, () => console.log('Uploader app listening on port 7000!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment