Skip to content

Instantly share code, notes, and snippets.

@shobhitg
Last active March 12, 2022 12:03
Show Gist options
  • Save shobhitg/5b367f01b6daf46a0287 to your computer and use it in GitHub Desktop.
Save shobhitg/5b367f01b6daf46a0287 to your computer and use it in GitHub Desktop.
File upload example using busboy with express
var path = require('path');
var fs = require('fs');
var os = require('os');
var express = require('express');
var app = express();
var Busboy = require('busboy');
app.get('/', function (req, res) {
res.send('<html><head></head><body>\
<form method="POST" enctype="multipart/form-data">\
<input type="text" name="textfield"><br />\
<input type="file" name="filefield"><br />\
<input type="submit">\
</form>\
</body></html>');
res.end();
});
// accept POST request on the homepage
app.post('/', function (req, res) {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var saveTo = path.join('.', filename);
console.log('Uploading: ' + saveTo);
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
console.log('Upload complete');
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
return req.pipe(busboy);
});
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
});
@mingybopeep
Copy link

the busboy package had a major version update earlier this year. I was having issues with +v1. I reverted to v0.4 and it's now working

@magnum6actual @stenes90 @mresmaeili @amindadgar

@vedantnd111
Copy link

don't use new keyword while creating busboy instance
wrong:
const bb=new busboy({headers:req.headers})
right:
const bb=busboy({headers:req.headers})

According to current version

@orivelton
Copy link

I updated to "connect-busboy": "0.0.3" and it's worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment