Skip to content

Instantly share code, notes, and snippets.

@carc1n0gen
Last active July 12, 2019 14:11
Show Gist options
  • Save carc1n0gen/073ae083988cf2d864894f8db26eef94 to your computer and use it in GitHub Desktop.
Save carc1n0gen/073ae083988cf2d864894f8db26eef94 to your computer and use it in GitHub Desktop.
How to read form fields before the file in a multipart upload
// 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