使用ASP.NET Web API返回图像并显示它? [英] return an image using ASP.NET Web API and display it?

查看:249
本文介绍了使用ASP.NET 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调用

响应-控制台中的数据

推荐答案

您无需对此操作进行AJAX调用.只需放置一个<img>标记并将其src属性指向您的Web API端点即可:

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="" />

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

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="" />');

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

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

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

这篇关于使用ASP.NET Web API返回图像并显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆