在生产中使用GridFS在节点中下载文件
我有一个快速的应用程序,这在我在本地运行时起作用。 问题是下载一个使用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'); });
这在玉文件中被这行所调用:
td #[a(href="getfile?id=#{log.videoId}" download="video") #[span(name='video').glyphicon.glyphicon-download]]
在服务器上,我正在做:
/logApp$ export NODE_ENV=production /logApp$ ./bin/www
mongoDB deamon正在运行。 其实我可以查询数据库。 而且我没有写任何文件! 我想读它。
编辑:我发现错误消息:
MongoError: file with id #### not opened for writing
您需要将用于pipe理文件的代码移动到gfs.exist
callback中,以便在存在检查之后运行。
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); });
显然,如果文件不存在,你会得到通用的“未打开”的错误。