C# ASP.NETWebAPI下载和查看图像
我想从服务器下载图像并在浏览器中显示它们。但是当我在浏览器中输入url(localhost:port/api/service/imageID)时,会出现下载框,询问我是保存还是打开图像。但我希望图像在浏览器中直接显示。 这是我的控制器“获取”方法:C# ASP.NETWebAPI下载和查看图像,c#,rest,asp.net-web-api,C#,Rest,Asp.net Web Api,我想从服务器下载图像并在浏览器中显示它们。但是当我在浏览器中输入url(localhost:port/api/service/imageID)时,会出现下载框,询问我是保存还是打开图像。但我希望图像在浏览器中直接显示。 这是我的控制器“获取”方法: public HttpResponseMessage Get(int id) { HttpResponseMessage response; var image = _repository.RetrieveImage(id); if (
public HttpResponseMessage Get(int id)
{
HttpResponseMessage response;
var image = _repository.RetrieveImage(id);
if (image == null)
{
response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
else
{
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(image.ImageData));
response.Content = new ByteArrayContent(image.ImageData);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = image.OriginalFileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(image.Mime);
response.Content.Headers.ContentLength = image.ImageData.Length;
}
return response;
非常感谢您的帮助请勿使用“附件”内容处置标题。使用该头指示浏览器下载指定的文件,而不是内联显示
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
对于您的场景,我认为您可以只返回一个StreamContent并提供此内容的适当内容类型头。(例如:image/jpeg)为了完整起见,请注意,当使用“另存为”上下文菜单保存文件时,删除
内容处置
也会删除任何关于文件名的提示,并且会根据URL建议一个文件名,在本例中类似于“42.jpg”,因为URL的最后一部分是ID。如果要在保存期间保留文件名,请将内容配置更改为“inline”:
我忍不住注意到您分配了内容
属性两次。你试过只使用StreamContent
吗?是的,但不起作用。我将尝试DigitalID的答案
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = image.OriginalFileName,
Size = image.ImageData.Length
};