简体   繁体   中英

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.

如果你使用jquery,你应该这样使用

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

You can also use this much shorter snippet.

$.get(MY_SERVICE_URL, function (base64string) {
    $("#myimage").attr("src", "data:image/jpg;base64," + base64string);
});

Assuming MY_SERVICE_URL only sends the exact result from return Convert.ToBase64String(ImgBytes); > /9j/4AAQSkZJRgABAQEASABIAAD/2wBD....

Thank you guys for the support. I was able to get through it.

This is what I did .,

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

function AjaxSucceeded(response) {
    $("#myimage").attr("src", "data:image/jpg;base64," + Response.GetCurrentFrameResult);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM