Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 string from ajax response to img tag

I have a WCF service which returns a base64 string equivalent of a bitmap image.

return Convert.ToBase64String(ImgBytes);

I am using ajax to invoke this service. The code is something like.,

jQuery.ajax({
     url: MY_SERVICE_URL,
     type: "GET",
     dataType: "html",
     success: AjaxSucceeded,
     error: AjaxFailed
});

function AjaxSucceeded(result, textStatus, request) {
    var binary = "";
    var responseText = request.responseText;
    var responseTextLen = responseText.length;

    for (i = 0; i < responseTextLen; i++) {
         binary += String.fromCharCode(responseText.charCodeAt(i) & 255);
    }

    $("#myimage").attr("src", "data:image/jpg;base64," + btoa(binary));
}

But i am not able to see any image.

Also i have tried using dataType as "text".

I have tried printing the data I am assigning to the src of the img tag. And i used that data here, where i am able to see the image.

Also i am able to view the image if i hard code the response value like.,

document.getElementById("myimage").src = "data:image/jpg;base64," + "Qk02EA4AAA...."

I have tried searching various forums. But unfortunately I am not able to figure this out. Am i missing something?

Thanks in advance.

like image 834
sam Avatar asked Dec 21 '25 17:12

sam


1 Answers

If you are using jquery, you should use like this

$("#myimage").attr("src","data:image/jpg;base64," + "Qk02EA4AAA....")
like image 92
Charles Stein Avatar answered Dec 23 '25 07:12

Charles Stein