使用Node.js检索Mongodb中存储的图像 [英] Retrieving Images stored in Mongodb with Nodejs

查看:87
本文介绍了使用Node.js检索Mongodb中存储的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have small thumbnails stored in a MongoDB collection. While I can extract them with a .findOne() I can not serve them back over an ExpressJS route correctly.

我没有在磁盘上存储大拇指,因为heroku环境不能保证持久存储.我没有使用GridFS,因为这些都是拇指<16MB.

I am not storing thumbs on disk as the heroku environment does not guarantee persisted storage. I am not using GridFS as these are thumbs < 16MB.

将一个新文档插入到集合中是这样的:

Inserting a a new document into the collection goes something like this:

 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 :

I can serve the img over an Expressjs route like this:

    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 返回这样的对象

The nodejs console.log returns an object like this,

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

但是浏览器控制台给我这样的错误:

But the browser console gives me an error like this:

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

我不正确地取消编码吗?错误设置 res 标头?

Am I incorrectly unencoding? Incorrectly setting res headers?

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

Can someone show me what I'm doing wrong?

推荐答案

因此,您看起来像在数据库中保存了base64映像.

So looks like you save a base64 image in your db.

您可以这样执行 img:Buffer(encImg).在node.js中,默认的Buffer编码为 utf8 ,因此您的映像将以MongoDB中二进制类型的base64 utf8字符串形式保存在db中!

You do this like this img: Buffer(encImg). In node.js default Buffer encoding is utf8, so your image is saved in db as a base64 utf8 string under binary type in MongoDB!

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

A proper way will be to specify a buffer encoding when you save your image:

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

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

That way when you send a response to client as res.send(results.img.buffer); you'll send binary data instead of a base64 string.

这篇关于使用Node.js检索Mongodb中存储的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆