我有一个存储在MongoDB集合中的小缩略图。虽然我可以使用.findOne()
来提取它们,但我无法正确地通过ExpressJS路线回送它们。用Nodejs检索存储在Mongodb中的图像
由于heroku环境不能保证持久存储,我不会在磁盘上存储大拇指。我没有使用GridFS,因为这些是大拇指< 16MB。
插入迈上了一个新文档到集合是这样的:
MongoClient.connect(url, function(err, db){
var newImg = fs.readFileSync(req.file.path);
var encImg = newImg.toString('base64');
var newItem = {
description: req.body.description,
date: Date(),
contentType: req.file.mimetype,
size: req.file.size,
img: Buffer(encImg)
};
db.collection('myimages')
.insert(newItem, function(err, result){
if (err) { console.log(err); }
});
});
我可以服务于img
了一个多Expressjs路线是这样的:
router.get('/pictures/:picture', function(req, res){
/* my filename is actually a mdb oid */
var filename = req.params.picture;
MongoClient.connect(url, function(err, db){
db.collection('myimages')
.findOne({'_id': ObjectId(filename)}, function(err, results){
console.log(results); //<-- Output below
res.setHeader('content-type', results.contentType);
res.send(results.img);
});
});
});
的的NodeJS console.log
返回一个对象像这样,
{ _id: 58f7ab923b7c842023cf80ec,
description: '',
date: 'Wed Apr 19 2017 13:25:22 GMT-0500 (CDT)',
contentType: 'image/jpeg',
size: 648436,
img:
Binary {
_bsontype: 'Binary',
sub_type: 0,
position: 864584,
buffer: <Buffer 2f 39 6a 2f 34 41 41 51 53 6b 5a 4a 52 67 41 42 41 51 41 41 53 41 42 49 41 41 44 2f 34 51 50 38 52 58 68 70 5a 67 41 41 54 55 30 41 4b 67 41 41 41 41 ... > }
}
但浏览器利弊OLE给了我这样的错误:
Resource interpreted as Document but transferred with MIME type image/jpeg: "http://localhost:3000/picturewall/58f7ab923b7c842023cf80ec".
我是不是正确unencoding?错误地设置res
标题?
有人可以告诉我我做错了什么吗?
你可以试试'res.send(results.img.buffer);'而不是'res.send(results.img);'? –
我刚试过这个,不幸的是(有点令人惊讶),它没有任何区别。甚至没有一个不同的错误。 – Colin
你还可以执行'curl localhost:3000/picturewall/...'并粘贴响应而不是浏览器截图? –