我想尝试使用Web API进行休息调用,但我希望响应是存储在数据库中的实际二进制映像,而不是JSON base64编码的字符串。有人对此有一些指示吗?
更新 - 这就是我最终实现的目标:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(profile.Avatar));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "avatar.png";
return result;
答案 0 :(得分:29)
您可以将响应内容设置为StreamContent对象:
var fileStream = new FileStream(path, FileMode.Open);
var resp = new HttpResponseMessage()
{
Content = new StreamContent(fileStream)
};
// Find the MIME type
string mimeType = _extensions[Path.GetExtension(path)];
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
答案 1 :(得分:18)
虽然这已被标记为已回答,但这并不是我想要的,所以我一直在寻找。现在我已经弄明白了,这就是我所拥有的:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
当然,这是通过URL获取图像。如果你只是想从文件服务器上取下一个图像,我想你会替换这一行:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
有了这个:
using (Bitmap image = new Bitmap(myFilePath))
编辑:没关系,这适用于常规MVC。对于Web API,我有这个:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
这与OP的相似。
答案 2 :(得分:1)
我做了这件事。这是我的代码:
if (!String.IsNullOrWhiteSpace(imageName))
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(uploadPath, imageName));
var image = System.Drawing.Image.FromFile(savedFileName);
if (ImageFormat.Jpeg.Equals(image.RawFormat))
{
// JPEG
using(var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Png.Equals(image.RawFormat))
{
// PNG
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Gif.Equals(image.RawFormat))
{
// GIF
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Gif);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
}
然后在客户端:
var client = new HttpClient();
var imageName = product.ImageUrl.Replace("~/Uploads/", "");
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Properties.Settings.Default.DeviceMediaPath + "\\" + imageName);
var response =
client.GetAsync(apiUrl + "/Image?apiLoginId=" + apiLoginId + "&authorizationToken=" + authToken +
"&imageName=" + product.ImageUrl.Replace("~/Uploads/","")).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
using (var ms = new MemoryStream(data))
{
using (var fs = File.Create(path))
{
ms.CopyTo(fs);
}
}
result = true;
}
else
{
result = false;
break;
}
答案 3 :(得分:0)
使用WebAPI,没有很容易实现此任务。我将为唯一扩展实现自定义HTTP handler,并在那里返回二进制响应。优点是您还可以修改HTTP响应标头和内容类型,这样您就可以完全控制返回的内容。
您可以设计一个网址格式(根据网址定义您知道要返回的图片的方式),并将这些网址保留在您的API资源中。一旦在API响应中返回了URL,它就可以被浏览器直接请求,并将到达您的HTTP处理程序,返回正确的图像。
图像是静态内容,在HTTP和HTML中有自己的作用 - 无需将它们与使用API时使用的JSON混合使用。