I am using MEAN stack and I am trying to serve a file stored using Mongo GridFs.
This is the code I have tried so far.
exports.getFile = function(req, res) {
var fileId = req.params.fileId;
gfs.findOne({ _id: fileId }, function (err, file) {
if (err) { res.status(500).send(err) }
console.log('file meta', file);
res.header("Content-Type", file.contentType);
var readstream = gfs.createReadStream({
filename: file.filename
});
//error handling, e.g. file does not exist
readstream.on('error', function (err) {
console.log('An error occurred!', err);
throw err;
});
readstream.on('close', function(file) {
console.log('file content', file);
});
readstream.pipe(res);
});
};
This is what I get on console:
file meta { _id: 566c0b6ddfb625ae52ce99c7,
filename: 'profile_picture_by_kyo_tux-d4hrimy.png',
contentType: 'binary/octet-stream',
length: 0,
chunkSize: 261120,
uploadDate: Sat Dec 12 2015 17:26:29 GMT+0530 (IST),
aliases: null,
metadata: null,
md5: 'd41d8cd98f00b204e9800998ecf8427e' }
file content undefined
GET /api/users/file/566c0b6ddfb625ae52ce99c7 200 9ms
I am not getting the file on webpage. What am I doing wrong?