2

I am retrieving an image which is stored as in binary form from mongoDB. and sending it as a json to jquery ajax. but console.log from node.js show it is fine but when request comes back to jquery ajax nothing happens, cannot see an image. And also image is saved in DB with type BUFFER. below is the code

jquery ajax code

$.ajax({
    url: config.ipaddress+'/getCompanyImage',
    contentType: 'image/png',
    type: 'GET',
    success: function(data, textStatus, jqXHR) {
        $.each(data, function(index, result) {
            alert('image result ' + result);
            $("#headerCompanyImage").attr("src", result);
        });

    },
    error: function (jqXHR, textStatus, errorThrown)
    {

    }
});

node.js code

exports.getCompanyImage = function(req,res) {
var_company.find({_id : req.session.company},function(err,company){
    company.forEach(function(companyLoop){
        console.log(companyLoop.company_image.contentType);
        console.log(companyLoop.company_image.data);
        res.contentType(companyLoop.company_image.contentType);
        res.json(companyLoop.company_image.data);
    })

  });
}
2
  • I think you can't return image as json... unless it's encoded as dataURL or base 64 or some other string, is that the case? Commented Jan 8, 2014 at 6:56
  • yes actually i am sending an image as json. Commented Jan 8, 2014 at 7:00

1 Answer 1

5

I have got the solution. It has to be in binary form and then convert it toString('base64') and then send the response. and now it is working

var img = new Buffer(companyLoop.company_image.data, 'binary').toString('base64');
res.contentType(companyLoop.company_image.contentType);
res.send(img);

and in jquery it would be

$("#headerCompanyImage").attr("src", "data:image/png;base64," + data);
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.