ASP .Net Web API 将图像下载为二进制文件 [英] ASP .Net Web API downloading images as binary
本文介绍了ASP .Net Web API 将图像下载为二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想尝试使用 Web API 进行休息调用,但我希望响应是存储在数据库中的实际二进制图像,而不是 JSON base64 编码的字符串.有人对此有所指点吗?
I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?
更新-这就是我最终实施的:
Update- This is what I ended up implementing:
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;
推荐答案
您可以将响应内容设置为 StreamContent 对象:
You can set the response content to a StreamContent object:
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);
这篇关于ASP .Net Web API 将图像下载为二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文