2012-10-21 86 views
26

我從asp.net網頁API嘗試下面的代碼,以輸出圖像,但響應的車身長度始終爲0輸出圖像使用Web API HttpResponseMessage

public HttpResponseMessage GetImage() 
{ 
    HttpResponseMessage response = new HttpResponseMessage(); 
    response.Content = new StreamContent(new FileStream(@"path to image")); 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); 

    return response; 
} 

任何提示嗎?

WORKS:

[HttpGet] 
    public HttpResponseMessage Resize(string source, int width, int height) 
    { 
     HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); 

     // Photo.Resize is a static method to resize the image 
     Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height); 

     MemoryStream memoryStream = new MemoryStream(); 

     image.Save(memoryStream, ImageFormat.Jpeg); 

     httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray()); 

     httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); 
     httpResponseMessage.StatusCode = HttpStatusCode.OK; 

     return httpResponseMessage; 
    } 
+0

不太確定,如果我得到你 - 但你可以檢查[**如何寫一個圖像outputStream **](http://stackoverflow.com/questions/5629251/c-sharp-outputting-image-to -response-output-stream-giving-gdi-error) –

+0

我沒有收到錯誤,我什麼也沒收到。 – lolol

+0

你回來了什麼狀態代碼? –

回答

5

的以下內容:

  1. 確保路徑是正確的(廢話)

  2. 確保您的路由是正確的。您的Controller可能是ImageController,或者您已經定義了一個自定義路由來支持其他控制器上的「GetImage」。 (你應該得到這個404響應)

  3. 確保您打開流:

    var stream = new FileStream(path, FileMode.Open);

我想類似的東西,它爲我工作。

+0

謝謝你,我的更新中的代碼工作。 – lolol

1

而不是ByteArrayContent,您還可以使用StreamContent類來更有效地使用流。