2013-02-19 72 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 
};