Wednesday, 19 April 2017

Retrieving Images stored in Mongodb with Nodejs

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

enter image description here

Am I incorrectly unencoding? Incorrectly setting res headers?

Can someone show me what I'm doing wrong?



via Colin

No comments:

Post a Comment