Skip to content

Instantly share code, notes, and snippets.

@psi-4ward
Created October 24, 2013 11:49
Show Gist options
  • Save psi-4ward/7135840 to your computer and use it in GitHub Desktop.
Save psi-4ward/7135840 to your computer and use it in GitHub Desktop.
Express example using busboy stream to GridFS
var uploader = function(req, res) {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, stream, filename, encoding, contentType) {
var pStream = pauseStream(); // use pause stream to have time to open the GridStore
stream.pipe(pStream.pause());
console.log('POST ' + req.originalUrl + ' File: '+ filename + ' Field: ' + fieldname);
cntProcessingFiles++;
new GridStore(db, null, filename , 'w', {content_type:contentType}).open(function(err, gridFile) {
if(err) console.log(err);
gridFile.on('close', function() {
gridFile.close(function(err, data) {
cntProcessingFiles--;
// do something with the gridfile
});
});
});
pStream.pipe(gridFile);
pStream.resume();
});
});
// form error (ie fileupload-cancel)
busboy.on('error', function(err) {
console.error(err);
res.send(500, 'ERROR', err);
});
// all uploades finished
function end() {
// wait until all files are finished
if(cntProcessingFiles > 0) {
setTimeout(end, 200);
return;
}
if(res.finished) return;
res.send('all done');
}
busboy.on('end', end);
// start parsing the HTTP-POST upload
req.pipe(busboy);
};
app.post('/upload', uploader);
@danielcosta27
Copy link

@tk2, this should be defined like this:

var pauseStream = require('pause-stream');

Please don't forget to install this module first, or put this package as a dependency in your package.json file.

;)

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