Search code examples
node.jspugnode-mongodb-native

Using binary data from Mongo collection as image source


I have an express app, storing data in mongo, using Jade as the view engine. I have a simple route that gets the docs in a particular collection, each doc corresponding to a product. The image is base64 encoded. When I try and render as an image though it doesn't work

My route is

exports.index = function(req, res){
   mongo.getProducts(function(data) {
      res.render('consumer/index', {user: req.session.user, products: data});
   });
};

The function that calls is

exports.getProducts = function(callback) {

   Product.find().exec(function(err, products){
      return callback(products);
   });
};

and then my Jade file has the following code

each val in products
  img(src="data:image/png;base64,'+#{val.image.data}+'", alt='Image', style="width: 20px; height: 20px")

Looking at the doc directly in Mongo (via robomongo) I get this

enter image description here

enter image description here

I don't know what I'm missing, because in another file I use jQuery datatables to show the documents, and the same approach there correctly renders the image, here is a snippet of the datatables code

"aoColumns": [
          {"mData": "name"},
          {"mData": "price"},
          {"mData": "category"},
          {"mData": "description"},
          {"mData": "image.data", "mRender": function ( data, type, full ) {
            return '<img src="data:image/png;base64,'+data+'", style="width: 20px; height: 20px"></>'}},
          {"mData": "promoted"},
          {"mData": null}
        ]

Solution

  • The problem is val.image.data doesn't provide a base64 string but a buffer. So, you have to convert it first. This is how I made it work:

    Product.findById('559f6e08b090ca5c5ce6942b', function(err, result) {
        if (err) throw (err);
    
        var thumb = new Buffer(result.image.data).toString('base64');
        res.render('index', { title: 'Express', img: thumb});
    });
    

    Also, there's a small issue on your frontend jade code, it should be:

    img(src="data:image/jpeg;base64,#{img}") //No + and ''

    Note: You could get away with this for small thumbnails or such but it is not the recommended approach due to a number of reasons (such as the 16MB limit). You are much better off using GridFS. More at http://docs.mongodb.org/manual/core/gridfs