Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# - return an image using ASP.NET Web API and display it?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...