Image 下载图像的最佳方法
我有一个简单的站点(WebAPI),它在get方法中返回一堆相册。每个专辑都有诸如标题、艺术家等属性。下面的属性是图像(相册照片)属性。每个相册都有一个图像,将图像发送回客户端的最佳方式是什么。它是否应该作为相册对象的一部分作为二进制数据发送,例如Image 下载图像的最佳方法,image,asp.net-web-api,Image,Asp.net Web Api,我有一个简单的站点(WebAPI),它在get方法中返回一堆相册。每个专辑都有诸如标题、艺术家等属性。下面的属性是图像(相册照片)属性。每个相册都有一个图像,将图像发送回客户端的最佳方式是什么。它是否应该作为相册对象的一部分作为二进制数据发送,例如 Public Class Album { string title; byte[] image; } 或者我应该发送相册对象中图像的路径,并让客户端单独下载图像 像 公开课相册 { 字符串标题; 字符串图像路径; }你可以参考这篇文
Public Class Album
{
string title;
byte[] image;
}
或者我应该发送相册对象中图像的路径,并让客户端单独下载图像
像
公开课相册
{
字符串标题;
字符串图像路径;
}你可以参考这篇文章
您可以使用FileStream
protected override void WriteFile(HttpResponseBase response) {
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream) {
byte[] buffer = new byte[_bufferSize];
while (true) {
int bytesRead = FileStream.Read(buffer, 0, _bufferSize);
if (bytesRead == 0) {
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}
而不是通过
Public class Album
{
string title;
byte[] image;
}
回到客户机,我将把image
更改为int-imageId
:
Public class Album
{
string Title{get;set};
int ImageId{get;set};
}
然后创建一个WebApi控制器,该控制器使用如下编写的方法处理图像:
public async Task<HttpResponseMessage> Get(HttpRequestMessage request, int imageId)
{
byte[] img = await _myRepo.GetImgAsync(imageId);
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(img)
};
msg.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return msg;
}
公共异步任务Get(HttpRequestMessage请求,int-imageId)
{
字节[]img=wait _myRepo.GetImgAsync(imageId);
HttpResponseMessage msg=新的HttpResponseMessage(HttpStatusCode.OK)
{
内容=新的ByteArrayContent(img)
};
msg.Content.Headers.ContentType=新的MediaTypeHeaderValue(“图像/png”);
返回味精;
}
谢谢你的指点。您还可以告诉我,在不同的请求中单独下载图像并在原始对象中发送路径或在原始对象本身中发送图像字节的最佳方法是什么?您希望用户下载您的图像吗?用户点击“下载”按钮,这些图像将被下载到用户的机器上。。或者,您只是在客户端站点(html和js)上显示这些图像吗?如果您只想在HTML页面上显示这些图像,那么返回图像链接列表是有意义的。我只想在客户端显示这些图像。因此,您的意思是将likn url发送到图像,然后分别下载每个图像?您可以从api发送url。。然后在客户端,将这些url设置为图像标记。。浏览器将自动下载图像。