【问题标题】:how to download a file saved in gridFS using nodeJS如何使用nodeJS下载保存在gridFS中的文件
【发布时间】:2016-01-07 05:29:46
【问题描述】:

我需要从 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】:

    希望这会有所帮助!

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

    【讨论】:

      【解决方案2】:

      我从接受的答案中得到了提示。但我不得不跳过一些障碍才能让它工作,希望这会有所帮助。

      const mongodb = require('mongodb');
      const mongoose = require('mongoose');
      const Grid = require('gridfs-stream');
      eval(`Grid.prototype.findOne = ${Grid.prototype.findOne.toString().replace('nextObject', 'next')}`);
      
      const mongoURI = config.mongoURI;
      const connection = mongoose.createConnection(mongoURI);
      
      app.get('/download', async (req, res) => {
          var id = "<file_id_xyz>";
          gfs = Grid(connection.db, mongoose.mongo);
      
          gfs.collection("<name_of_collection>").findOne({ "_id": mongodb.ObjectId(id) }, (err, file) => {
              if (err) {
                  // report the error
                  console.log(err);
              } else {
                  // detect the content type and set the appropriate response headers.
                  let mimeType = file.contentType;
                  if (!mimeType) {
                      mimeType = mime.lookup(file.filename);
                  }
                  res.set({
                      'Content-Type': mimeType,
                      'Content-Disposition': 'attachment; filename=' + file.filename
                  });
      
                  const readStream = gfs.createReadStream({
                      _id: id
                  });
                  readStream.on('error', err => {
                      // report stream error
                      console.log(err);
                  });
                  // the response will be the file itself.
                  readStream.pipe(res);
              }
          });
      

      【讨论】:

        猜你喜欢
        • 2014-04-19
        • 2020-07-13
        • 2013-09-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        • 2012-11-10
        • 1970-01-01
        相关资源
        最近更新 更多