0

I have an image (png) file stored in my MongoDB as binary data. My MongoDB schema looks like below :

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ImageSchema = new Schema (
{ title : String,
  picture: { content: Buffer, contentType: String }
}
);

The mustache code looks like below:

var template = "{{picture.content}} <h1>{{title}}</h1>";
var rendered = Mustache.render(template, imageObject);
$('#target').html(rendered);

The data in MongoDB looks like below, it has been shortened as it is too long:

 "picture" : {
                "contentType" : "image/png",
                "content" : BinData(0,"iVBORw0KGgoAAAANSUhEUg ...")
             }

Below is how I am storing it into MongoDB using multer :

dbmodel.findOne(req.params.title, function(err, ) {
 records.picture.content = fs.readFileSync(req.files.path);
        records.picture.contentType = 'image/png';
        records.save(function (err) {
          if(!err) {
            res.send("Image is saved into MongoDB");

          } else {
            res.send(400).send();
          }
 })

What is the way to convert this binary data to image and especially fit it into the Mustache template for display ? Also please let me know if the image needs to be saved in some other way and how for easier display using Mustache.

Thanks.

4
  • 2
    well you can't render binary data to an image like that instead just create an route for rendering images from binary data returning proper http headers use the image src attribute to point to the route. I believe though that storing images like that will stress your server a lot, use some kind of storage way that stores to files and also handles caching and stuff. Commented Apr 10, 2017 at 15:07
  • @Mr.Phoenix Thanks for your reply, I have added some more code about how am I saving it into MongoDB, could you please put some example code to explain your idea ? Commented Apr 10, 2017 at 15:13
  • @Mr.Phoenix As an alternative way I am using the fs.writeFile code from this link stackoverflow.com/a/37091088/6038082 , could you please tell me what should I put in place of base64data as the second argument to writeFile ? Commented Apr 10, 2017 at 18:01
  • If anybody has a working code to save the actual image into MongoDB so as to render it later using Mustache , please help me with that. Commented Apr 10, 2017 at 18:02

1 Answer 1

0

Convert binary data into image by converting it to a URL and then feeding to src of <img> tag-

var template="<img src={{{`data:image/png;base64,${picture.content}`}}}/> <h1>{{title}}</h1>";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.