Retrieving Images stored in Mongodb with Nodejs

十年热恋 提交于 2021-02-11 11:52:45

问题


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.

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); }
                });
});

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);     
        });
    });
    });

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

Am I incorrectly unencoding? Incorrectly setting res headers?

Can someone show me what I'm doing wrong?


回答1:


So looks like you save a base64 image in your 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')
// ...

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.



来源:https://stackoverflow.com/questions/43503963/retrieving-images-stored-in-mongodb-with-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!