I have an image saved on a MongoDB. The model is the following:
picture: {
metadata: {
name: { type: String, default: null },
comment: { type: String, default: null },
publisherID: { type: String,default: null },
date: { type: Date, default: Date.now },
size: { type: Number,default: 0 },
type: { type: String, default: null }
},
data: { type: Buffer, default: null },
tags: Array
}
Now I need to load the image again from the DB.
I make an AJAX call and request the picture with the id.
$.ajax({
type: "POST",
url: window.location.origin + '/picture',
contentType: 'application/json',
dataType: 'json',
async: true,
data: JSON.stringify({ id: id }),
success: function (result) {
console.log(result);
a = result;
var img = result.result[0].picture.data.join("").toString('base64');
img = "data:" + result.result[0].picture.metadata.type + ";base64," + img;
$('#img').attr('src', img);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus + " " + errorThrown);
success = false;
}
});
And this is the handler on the server
var Picture = require('../models/picture');
Picture.find({ "_id": req.body.id}, function (err, pic) {
if (err || !pic)
res.end(JSON.stringify({ result: "error" }));
if (pic) {
console.log(pic);
res.end(JSON.stringify({ result: pic }));
}
})
I have translated the binary data into base64 but the image doesnt display. (I had to join the binary data because they came into an array). There are some other similar posts however they dont have anything that I havent done (I think).