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

2019-07-23 17:36发布

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条回答
小情绪 Triste *
2楼-- · 2019-07-23 17:44

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.

查看更多
登录 后发表回答