node.js - 使用 Nodejs 检索存储在 Mongodb 中的图像

标签 node.js mongodb express base64 mime-types

我有一些小缩略图存储在 MongoDB 集合中。虽然我可以使用 .findOne() 提取它们,但我无法通过 ExpressJS 路由正确地将它们返回。

我不会将拇指存储在磁盘上,因为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".

enter image description here

我是否错误地取消了编码? res header 设置不正确?

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

最佳答案

看起来您在数据库中保存了一个 Base64 图像。

你这样做img: Buffer(encImg) 。在node.js中默认的Buffer编码是utf8 ,所以你的图像在MongoDB中以二进制类型保存在db中!

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

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

这样,当您将响应发送给客户端时 res.send(results.img.buffer);您将发送二进制数据而不是 Base64 字符串。

关于node.js - 使用 Nodejs 检索存储在 Mongodb 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43503963/

相关文章:

javascript - 如何在虚拟数据类型中使用 JSONB 数据?

javascript - 是否可以使用标记模板文字并将模板文字保存为常量?

javascript - Node.js 中的 MongoDB 分页(带排序)

javascript - ~[Array].indexOf(key) 是做什么的?

node.js - `Extensions` 字段未显示在 apollo graphql 响应数据中

node.js - 在 nodejs 和管道中生成 ffmpeg 以表达的响应

mysql - Mysql连接超时与回送服务器

javascript - 引用错误 : NumberDecimal is not defined in mongoDB

c# - C#中的MongoDB聚合函数

node.js - 在 expressjs PEM 例程 :PEM_read_bio:no start line 上设置 https