2014-09-25 95 views
2

我有一個簡單的網站(WebAPI),它返回get方法中的一堆相冊。每張專輯都有屬性,如標題,藝術家等。這裏的屬性是圖片(相冊照片)屬性。每張專輯都有一張圖片,將圖片發回客戶端的最佳方式是什麼?如果它被作爲二進制數據發送作爲專輯的對象,例如像下載圖像的最佳方法

Public Class Album 
{ 
    string title; 
    byte[] image; 
} 

或者我應該送的路徑,圖像中的物體專輯,並有客戶端單獨下載圖像的一部分?

Like Public Class Album { string title; string imagePath; }

回答

0

你可以看到這篇文章The downloaded file as stream in controller (ASP.NET MVC 3) will automatically disposed?作爲參考。

您可以使用FileStream。

protected override void WriteFile(HttpResponseBase response) { 
    // grab chunks of data and write to the output stream 
    Stream outputStream = response.OutputStream; 
    using (FileStream) { 
     byte[] buffer = new byte[_bufferSize]; 
     while (true) { 
      int bytesRead = FileStream.Read(buffer, 0, _bufferSize); 
      if (bytesRead == 0) { 
       // no more data 
       break; 
      } 
      outputStream.Write(buffer, 0, bytesRead); 
     } 
    } 
} 
+0

感謝您的指針。你還可以告訴我什麼是最好的方法分別在不同的請求中下載圖像,並在原始對象中發送路徑或在原始對象本身中發送圖像字節? – user3547774 2014-09-25 09:44:01

+0

你想讓用戶下載你的圖片嗎?像用戶將點擊「下載」按鈕,這些圖像將被下載到用戶的機器。或者,你只是在客戶端網站(HTML和JS)顯示這些圖像?如果你只是想在HTML頁面上顯示這些圖像,那麼返回圖像鏈接列表是有意義的。 – 2014-09-25 10:00:37

+0

我只想在客戶端顯示圖像。那麼你所說的是將圖像發送到圖像,然後分別下載每個單獨的圖像? – user3547774 2014-09-25 10:24:53

0

不是傳遞

Public class Album 
{ 
    string title; 
    byte[] image; 
} 

返回給客戶端的,我會改變imageint imageId

Public class Album 
{ 
    string Title{get;set}; 
    int ImageId{get;set}; 
} 

然後創建一個的WebAPI控制器與這樣寫的方法處理圖像這個:

public async Task<HttpResponseMessage> Get(HttpRequestMessage request, int imageId) 
    { 

     byte[] img = await _myRepo.GetImgAsync(imageId); 

     HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK) 
     { 
      Content = new ByteArrayContent(img) 
     }; 
     msg.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); 

     return msg; 
    }