node.js - 在生产中使用 GridFS 在 Node 中下载文件

标签 node.js mongodb express

我有一个 express 应用程序,当我在本地运行时它可以工作。问题是在使用 GridFS 下载保存在 mongoDB 中的文件时。在本地运行它时(我只是执行 ./bin/www 并转到 localhost:3000),我可以下载该文件。但是当我远程运行它时,我下载了一个 html 文件。

这是处理响应的路由:

router.get('/getfile',function(req,res) {
    if (req.isAuthenticated())
    {
            var gfs = Grid(mongoose.connection, mongoose.mongo);
            var id = req.query.id;
            gfs.exist({_id: id}, function (err, found) {
                if (err) return handleError(err);
                if (!found)
                    res.send('Error on the database looking for the file.')
            });

            var readStream = gfs.createReadStream({
                _id: id
            }).pipe(res);
    }
    else
        res.redirect('/login');
});

jade 文件中的这一行调用了它:

td #[a(href="getfile?id=#{log.videoId}" download="video") #[span(name='video').glyphicon.glyphicon-download]]

在服务器上,我正在做:

/logApp$ export NODE_ENV=production
/logApp$ ./bin/www 

mongoDB 守护进程正在运行。事实上,我可以查询数据库。而且我没有写任何文件!我想读它。

编辑:我发现错误信息:

MongoError: file with id #### not opened for writing

最佳答案

您需要将通过管道将文件传输到响应的代码移动到 gfs.exist 回调中,以便它在存在检查之后运行。

gfs.exist({ _id: id }, function(err, found) {
    if (err) {
      handleError(err); 
      return;
    }

    if (!found) {
      res.send('Error on the database looking for the file.')
      return;
    }

    // We only get here if the file actually exists, so pipe it to the response
    gfs.createReadStream({ _id: id }).pipe(res);
});

显然,如果文件不存在,您会收到一般性的“未打开写入”错误。

关于node.js - 在生产中使用 GridFS 在 Node 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35203928/

相关文章:

javascript - 如何使用 sinon stub /模拟 Nodejs 需求的子模块

python - 获取查询返回的文档数

javascript - Mongo 检查文档是否已存在

mysql - 如果另一个表中不存在则添加用户

node.js - 带有两个字段和一个搜索参数的 mongoose find() 文档

node.js - 如何将 Node 应用程序转换为 VS Code 扩展程序?

node.js - SSE - 服务器发送的事件 - 如何重用相同的 EventSource

mongodb - node.js - 无法让 mongodb 工作,可能安装错误?

node.js - 如何在 azure 网站上将私有(private) git 存储库作为包加载?

node.js - 是否可以不向人们正在测试我的 Node/express 站点的 URL 发送响应?