如何使用nodeJS下载保存在gridFS中的文件

问题描述 投票:3回答:1

我需要从GridFS下载一个简历,下面是我写的代码,但是这似乎没有给我一个物理文件供下载,这用于阅读内容。我该如何下载文件?

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);
});
};
node.js mongodb gridfs
1个回答
5
投票

希望这可以帮助!

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);
  });
};
© www.soinside.com 2019 - 2024. All rights reserved.