尝试使用route:
从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访问。
答案 0 :(得分:0)
所以,我要做的就是设置我的数据库连接:
mongoose.connect(mongodb_url, { useMongoClient: true });
var db = mongoose.connection;
db.options = {};
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.info('database connection successful');
});
“db.options = {};”是踢球者。