使用ASP.NET Web API返回图像并显示它?

时间:2017-01-07 09:43:12

标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2

web api行动:

byte[] bytes = System.IO.File
                        .ReadAllBytes(
                          HttpContext.Current.Server.MapPath("~/Images/orderedList1.png"));
var result_ = new HttpResponseMessage(HttpStatusCode.OK);
result_.Content = new ByteArrayContent(bytes);
result_.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result_;

Ajax call enter image description here

respond - data in console enter image description here

1 个答案:

答案 0 :(得分:4)

您无需对此操作进行AJAX调用。只需添加<img>标记并将其src属性指向Web API端点:

<img src="api/account/GetImageByAccountId/12345" alt="" />

或者如果您事先不知道accountId,则可以动态构建此img标记,并使用javascript将其注入DOM:

var id = '12345';
$('#someDivId').prepend('<img src="api/account/GetImageByAccountId/' + id + '" alt="" />');

,图像将添加到您需要在DOM中的容器中:

<div id="someDivId"></div>