用Nodejs检索存储在Mongodb中的图像

我有一个小的缩略图存储在一个MongoDB集合。 虽然我可以用.findOne()提取它们,但是我无法正确地将它们返回到ExpressJSpath。

我不会在磁盘上存储大拇指,因为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); } }); }); 

我可以像这样通过Expressjs路线服务img

  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 ... > } } 

但浏览器控制台给我这样一个错误:

 Resource interpreted as Document but transferred with MIME type image/jpeg: "http://localhost:3000/picturewall/58f7ab923b7c842023cf80ec". 

在这里输入图像说明

我错误地解密? 错误地设置res标题?

有人能告诉我我做错了什么吗?

所以看起来像你在你的数据库中保存一个base64图像。

你可以这样做img: Buffer(encImg) 。 在node.js中默认的缓冲区编码是utf8 ,所以你的图像在MongoDB中以二进制types作为base64 utf8string保存在db中!

正确的方法是在保存图像时指定一个缓冲区编码:

 // ... img: new Buffer(encImg, 'base64') // ... 

这样,当你发送一个响应客户端作为res.send(results.img.buffer); 您将发送二进制数据而不是base64string。