set an image sent as binary data from node.js in jquery ajax

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

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);
    })

  });
}

Problem courtesy of: JN_newbie

Solution

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);

Solution courtesy of: JN_newbie

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章