Webapi返回使用jquery Ajax方法显示的二进制图像

时间:2014-05-25 03:21:37

标签: jquery ajax asp.net-web-api

我有以下webapi方法

    public HttpResponseMessage GetImage()
    {
        string imgUri = HttpContext.Current.Server.MapPath("~/Images/htmllogo.png");
        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StreamContent(new FileStream(imgUri, FileMode.Open));

        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

        return response;
    }

我也有以下html

 <div><button id="loadImage">Load</button></div>
<div id="divImageHolder"></div>

我正在使用jquery的Ajax方法来检索我的图像:

$("#loadImage").click(function () {
        var options = {};
        options.url = "api/mywebapi/GetImage";
        options.type = "GET";
        //options.dataType = "image/png";
        options.contentType = "image/png";
        options.success = function (results) {          
            var imag = "<img " + "src='" + results + "'/>";

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

        };
        options.error = function (jqXHR, textStatus, errorThrown)
        {
            console.log(errorThrown);
        };
        $.ajax(options);
    });    

点击按钮后我看到的是二进制垃圾&#39;在divImageHolder div中。没有显示图像

我尝试添加&#34;数据:image / png; base64&#34;在结果之前的src属性但是没有用。我认为原因是base64是文本编码,但我收到的是二进制数据。

如果我使用Json并将图像转换为base64编码(在web api方法中),那么它工作正常但是我无法设法让它与二进制一起使用,即我的web api方法正在返回StreamContent。 / p>

options.dataType是故意注释掉的,因为它除了json之外不接受任何东西。如果我取消注释它,我将收到错误。错误是&#34;没有从文本转换为图像/ png&#34;但如果我把它留下注释掉,我设法得到成功的方法,我可以看到二进制结果

谢谢

1 个答案:

答案 0 :(得分:1)

This post here by @gaetanoM should solve this problem, basically by doing the base64 converson in the javascript

还有&#39; mimeType:&#34; text / plain;字符集= X-用户定义&#34;&#39;可能是必要的。