在mvc控制器的动作中返回图像字节数组并在javascript

时间:2018-02-14 04:47:11

标签: javascript asp.net-mvc image

在MVC中,我们将从服务器获取图像并在客户端显示它,控制器中的GetImage Action如下:

public byte[] GetImage()
{
    byte[] imgByteArray=File.ReadAllBytes("Img1.jpeg");
    return imgByteArray  ;          
}

客户端的javascript代码如下:

$.ajax(
...
  success: function (response) {
                $('#imgResult')
                 .attr('src', 'data:image/jpeg;base64,' + response);
           },
    error: function (er) {
                        alert(er);
          }

成功接收响应但未显示图像且src值设置为:

src="data:image/jpeg;base64,System.Byte[]"

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

经过测试和运作的代码:

控制器:

    [HttpGet]
    public JsonResult GetImage()
    {
        System.Drawing.Image img = 
        System.Drawing.Image.FromFile(@"D:\yourimagepath.PNG");
        byte[] bytes;
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            bytes = ms.ToArray();
        }

        return Json(new { base64imgage = Convert.ToBase64String(bytes) }
          , JsonRequestBehavior.AllowGet);
    }

Ajax电话:

  $.ajax({
        .....

      success: function (data) {

            var imag = "<img "
            + "src='" + "data:image/png;base64,"
            + data.base64imgage + "'/>";

            $("#imgResult").html(imag);

            //here imgResult is Div id and inside img is getting created.

        }

        });