使用Javascript(MVC)加载图像(字节数组)的数据库 [英] Javascript (MVC) load image (byte array) from database

查看:220
本文介绍了使用Javascript(MVC)加载图像(字节数组)的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多回答这个问题在这里对堆栈,但他们都不是为我工作...

There are many answers to this question here on Stack but none of them are working for me...

我需要从一个字节数组,我通过我的控制器Ajax调用正在检索设置图像标签的JavaScript中的src属性。我必须这样做客户端,因为我是动态生成一些HTML(未在下面我简单的例子所示)

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)

下面是这个视图:

<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>

下面是脚本:

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);
        }
    });
}

正确地在imgFromModel的标签的图像的负载,但不能从脚本(imgFromScript的标签)一样。是否有人可以告诉我如何加载(设置SRCattr)使用从控制器方法的字节数组转换为图像标记?

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?

感谢您在您的帮助

推荐答案

很多上场后,一个良好的夜间睡眠和一点点运气,这里是解决方案。

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

我需要一个字符串属性添加到我的模型,把它称为ImageBytesAsString,并设置src中,在我的Ajax响应。这里是code ..

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; }

控制器:

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

JavaScript的:

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);
    }
});

查看:

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

我希望这可以帮助别人。

I hope this helps someone.

这篇关于使用Javascript(MVC)加载图像(字节数组)的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆