Last active
July 12, 2019 14:11
-
-
Save carc1n0gen/073ae083988cf2d864894f8db26eef94 to your computer and use it in GitHub Desktop.
How to read form fields before the file in a multipart upload
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
// NOTE: this only works if the file upload form field appears last | |
const busboy = require('connect-busboy'); | |
const express = require('express'); | |
const app = express(); | |
app.use(busboy()); | |
app.post('/upload', (req, res) => { | |
if (req.busboy) { | |
req.busboy.on('field', (fieldName, fieldVal) => { | |
req.pause(); // pause the request stream while we do something with this field | |
// Do whatever | |
console.log(`${fieldName}: ${fieldVal}`); | |
// Simulate a long running task to do before resuming the request stream | |
for (let n = 0; n < 1000000000; ) { n += 1 } | |
req.resume(); // resume the request stream once we are done here | |
}); | |
req.busboy.on('file', (fieldName, fileStream, fileName, encoding, mimeType) => { | |
console.log(`file: ${fileName}`); | |
fileStream.pipe(res); | |
}); | |
req.pipe(req.busboy); | |
} else { | |
res.send('No file'); | |
} | |
}); | |
app.listen(6060, () => console.log('serving...')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment