Javascript (MVC) load image (byte array) from data

2019-07-23 17:11发布

问题:

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

回答1:

After a lot of playing, a good night's sleep and a bit of luck, here is the solution.

I needed to add a string property to my model, call it "ImageBytesAsString" and set the src to that in my ajax response. Here is the code..

MODEL:

public byte[] Image { get; set; }
public string ImageBytesAsString { get; set; }

CONTROLLER:

var user = context.Users.FirstOrDefault();
user.ImageBytesAsString = Convert.ToBase64String(user.Image);

JAVASCRIPT:

    $.ajax({
    url: "/Home/LoadFromDatabase",
    async: true,
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        $("#imgFromScript").attr("src", "data:image/png;base64," + response.ImageBytesAsString);
    }
});

VIEW:

<img id="imgFromScript" src="#" alt=""/>

I hope this helps someone.