how to download a file saved in gridFS using nodeJS

前端 未结 2 572
长情又很酷
长情又很酷 2020-12-19 10:51

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 cont

2条回答
  •  不知归路
    2020-12-19 11:25

    Hope this helps!

    exports.getFileById = function(req, res){
    var role = req.session.user.role;
    var conn = mongoose.connection;
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.findOne({ _id: req.params.ID, root: 'resume' }, 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: req.params.ID,
          root: 'resume'
        });
    
        readstream.on("error", function(err) { 
            res.end();
        });
        readstream.pipe(res);
      });
    };
    

提交回复
热议问题