我有一个 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/