When the following POST API is called, it should save the file to the file system. However, the file is not being saved. I can see the file in the console, but can't save/write it. I have the following code:
router.post('/notes', function(req, res, next) {
var gfsstream, startFileWrite, endFileWriteTime;
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
startFileWrite = new Date().getTime();
console.log('File [' + fieldname + ']: filename: ' + filename);
gfsstream = gfs.createWriteStream('/uploads');
file.on('data', function(data) {
gfsstream.write(data);
});
file.on('end', function() {
gfsstream.end();
req.pipe(gfsstream);
});
gfsstream.on('close', function (file) {
// do something with `file`
endFileWrite = new Date().getTime();
console.log('File [' + fieldname + '] Finished');
console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms");
});
});
busboy.on('error', function(err) {
console.error(err);
res.sendStatus(500, 'ERROR', err);
});
busboy.on('finish', function end() {
res.sendStatus(200);
});
req.pipe(busboy);
});
req.pipe(gfsstream)
might be the issue here, but I am not sure what is preventing the file from being saved.
Just do file.pipe(gfsstream)
and use the finish
event instead of the close
event:
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
startFileWrite = new Date().getTime();
console.log('File [' + fieldname + ']: filename: ' + filename);
gfsstream = gfs.createWriteStream('/uploads');
file.pipe(gfsstream).on('finish', function() {
endFileWrite = new Date().getTime();
console.log('File [' + fieldname + '] Finished');
console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With