return an image using ASP.NET Web API and display

2019-06-14 15:55发布

web api action :

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条回答
手持菜刀,她持情操
2楼-- · 2019-06-14 16:15

You don't need to make an AJAX call to this action. Just put an <img> tag and point its src property to your Web API endpoint:

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

or if you don't know the accountId in advance, you could construct this img tag dynamically and inject it into the DOM using javascript:

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

and the image will be added to a container that you need to have in your DOM:

<div id="someDivId"></div>
查看更多
登录 后发表回答