如何使用nodeJS下载保存在gridFS中的文件 [英] how to download a file saved in gridFS using nodeJS

查看:90
本文介绍了如何使用nodeJS下载保存在gridFS中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从GridFS下载简历,以下是为此目的编写的代码ive,但这似乎并没有给我提供下载的物理文件,而是用于读取内容的.如何下载文件?

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);
});
};

推荐答案

希望这会有所帮助!

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);
  });
};

这篇关于如何使用nodeJS下载保存在gridFS中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆