2017-04-19 25 views
1

我有一个存储在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". 

enter image description here

我是不是正确unencoding?错误地设置res标题?

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

+0

你可以试试'res.send(results.img.buffer);'而不是'res.send(results.img);'? –

+0

我刚试过这个,不幸的是(有点令人惊讶),它没有任何区别。甚至没有一个不同的错误。 – Colin

+0

你还可以执行'curl localhost:3000/picturewall/...'并粘贴响应而不是浏览器截图? –

回答

1

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

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

一种合适的方式将是指定一个缓冲区编码时,您保存图片:

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

这样,当您发送到客户端为res.send(results.img.buffer);您要发送的,而不是一个base64字符串二进制数据的响应。

+0

非常感谢你弗拉德。我很感激你花时间和我一起看这个。 – Colin

+0

不客气,科林。 –