There are many answers to this question here on Stack but none of them are working for me...
I need to set the "src" attribute of an image tag in javascript from a byte array that I am retrieving via an ajax call to my controller. I have to do this client side because I am dynamically building some of the html (not shown in my simple example below)
Here is the view:
<div>
<button onclick=" loadFromDb(); ">CLICK ME</button>
<img id="imgFromModel" src="data:image/png;base64,@Convert.ToBase64String(Model.Image)" alt="" />
<img id="imgFromScript" src="#" alt=""/>
</div>
Here is the script:
function loadFromDb() {
$.ajax({
url: "/Home/LoadFromDatabase",
async: true,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
var base64String = btoa(response.Image);
$("#imgFromScript").attr("src", "data:image/png;base64," + base64String);
}
});
}
The image loads correctly in the "imgFromModel" tag, but doesn't from the script (the "imgFromScript" tag). Can someone please tell me how to load (set the "src" attr) a byte array from a controller method into an image tag?
Thank you in advance for your help