2014-05-25 44 views
2

显示我有以下的WebAPI方法的WebAPI返回二进制图像使用jQuery的Ajax方法

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

我在点击按钮后看到的是'binary garbage'in divImageHolder di诉没有图像正在显示

我已经尝试在结果之前向src属性中添加“data:image/png; base64”,但没有奏效。我认为原因是base64是文本编码,但我收到的是二进制数据。

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

options.dataType被故意注释掉,因为它不接受除json之外的任何内容。如果我没有注释它,我会得到一个错误。错误是“从文本到影像/ PNG没有转换”,但如果我离开它注释掉我设法得到成功的方法,在那里我可以看到二进制结果

谢谢

+0

你正在设置结果数据的图像...如果你只是调用get,然后将图像的源设置为url ... – Phill

+0

你能详细说明这个吗?你可以用代码写下来吗?请注意,Web API是返回HttpResponseMessage –

+0

您的建议工作,我只是试过它,但我仍然想看看是否有一种方法使用检索的二进制数据显示图像使用jQuery的Ajax方法 –

回答