2013-02-19 75 views
1

我想从服务器下载图像并在浏览器中显示它们。但是当我在浏览器中输入url(localhost:port/api/service/imageID)时,下载框会出现,要求我保存或打开图像。但我希望图像能够直接显示在浏览器中。 这是我的控制器“获得”的方法:ASP .net Web Api下载和查看图像

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; 

非常感谢您的帮助

+0

我不禁注意到,你指定'Content'性能的两倍。你有没有尝试过使用'StreamContent'? – 2013-02-19 00:09:17

+0

是的,我做了,但它不起作用。我会尝试从DigitalID – aimyas 2013-02-19 00:16:42

回答

2

不要使用“附件”内容处置头。使用该标头指示浏览器下载指定的文件,而不是以内联方式显示。

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
+0

的答案它的作品,非常感谢你 – aimyas 2013-02-19 00:24:10

0

对于你的情况,我想你可以只返回一个StreamContent,并提供该内容的适当的Content-Type头。 (例如:image/jpeg)

0

为了保持完整性,请注意,删除Content-Disposition时,如果使用“另存为”上下文菜单保存,则会删除文件名的任何提示,并根据URL建议文件名在这种情况下将会像“42.jpg”一样,因为URL的最后部分是一个ID。如果你想保存过程中保存的文件名,改变Content-Disposition为“内联”:

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline") 
{ 
    FileName = image.OriginalFileName, 
    Size = image.ImageData.Length 
};