node.jsmongodbgridfs

how to download a file saved in gridFS using nodeJS


I need to download a resume from GridFS, below is the code ive written to do it, but this seems to not give me a physical file for download, this is used to reading the contents. How can i download the file?

exports.getFileById = function(req, res){
var conn = mongoose.connection;
var gfs = Grid(conn.db, mongoose.mongo);
var id = req.params.ID;
gfs.exist({_id: id,root: 'resume'}, function (err, found) {
    if (err) return handleError(err);
    if (!found)
        return res.send('Error on the database looking for the file.');
    gfs.createReadStream({_id: id,root: 'resume'}).pipe(res);
});
};

Solution

  • Hope this helps!

    exports.downloadResume = function(req, res){
    var conn = mongoose.connection;
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.findOne({ _id: <resumeId>, root: <collectionName> }, function (err, file) {
        if (err) {
            return res.status(400).send(err);
        }
        else if (!file) {
            return res.status(404).send('Error on the database looking for the file.');
        }
    
        res.set('Content-Type', file.contentType);
        res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');
    
        var readstream = gfs.createReadStream({
          _id: <resumeId>,
          root: '<collectionName>'
        });
        
        readstream.on("error", function(err) { 
            res.end();
        });
        readstream.pipe(res);
      });
    };