尝试使用路由从 MongoDB 下载图像文件:
router.get('/:id', function(req, res) {
gfs.findOne({ _id: mongoose.Types.ObjectId(req.params.id) }, function(err, file) {
if (err) {
common.handleError(err, res);
return;
}
if (!file) {
return res.json({ status: constants._ERROR, body: { message: constants._FILE_NOT_FOUND }});
}
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');
//console.log(file);
var readstream = gfs.createReadStream({
_id: file._id
});
readstream.on('error', function (err) {
console.error('Read error', err);
res.end();
});
readstream.pipe(res);
});
});
堆栈跟踪:
/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/mongodb/lib/utils.js:123
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property 'readPreference' of null
at new GridStore (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/mongodb/lib/gridfs/grid_store.js:130:66)
at new GridReadStream (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/gridfs-stream/lib/readstream.js:68:17)
at Grid.createReadStream (/Users/eric.miles/Projects/Personal/mean/emcontacts/node_modules/gridfs-stream/lib/index.js:53:10)
at /Users/eric.miles/Projects/Personal/mean/emcontacts/server/routes/file.js:51:26
版本:
"gridfs-stream": "^1.1.1",
"mongoose": "^4.11.13"
在 createReadStream 行上搞砸了。文件肯定在数据库中,“fs.files & fs.chunks”。
现在尝试通过 Postman 访问。