Last active
March 15, 2018 04:03
-
-
Save good-idea/60b6f5197a924f3d2544c628a19e84f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Dependencies | |
*/ | |
const express = require('express') | |
const Multer = require('multer') | |
const Busboy = require('busboy') | |
const os = require('os') | |
const fs = require('fs') | |
const path = require('path') | |
const app = express() | |
app.get('/', (req, res, next) => res.json({ cool: true })) | |
app.post('/upload', (req, res, next) => { | |
console.log('upload?') | |
console.log(req.rawBody) | |
const busboy = new Busboy({ headers: req.headers }) | |
// This object will accumulate all the uploaded files, keyed by their name. | |
const uploads = {} | |
const tmpdir = os.tmpdir() | |
// This callback will be invoked for each file uploaded. | |
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { | |
console.log(`got file ${filename}`) | |
// Note that os.tmpdir() is an in-memory file system, so should | |
// only be used for files small enough to fit in memory. | |
const filepath = path.join(tmpdir, filename) | |
console.log(filepath) | |
uploads[fieldname] = filepath | |
file.pipe(fs.createWriteStream(filepath)) | |
}) | |
// This callback will be invoked after all uploaded files are saved. | |
busboy.on('finish', () => { | |
// *** Process uploaded files here *** | |
for (const name in uploads) { | |
const file = uploads[name] | |
fs.unlinkSync(file) | |
} | |
return res.json({ message: `file uploaded` }) | |
res.end() | |
}) | |
busboy.end(req.rawBody) | |
}) | |
module.exports = { app } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment