2013-02-04 28 views
14

我們試圖使用ASP.Net WebApi返回大型圖像文件,並使用以下代碼將字節傳輸到客戶端。使用ASP.Net Webapi流式傳輸大圖像

public class RetrieveAssetController : ApiController 
{ 

    // GET api/retrieveasset/5 
    public HttpResponseMessage GetAsset(int id) 
    { 
     HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); 
     string filePath = "SomeImageFile.jpg"; 

     MemoryStream memoryStream = new MemoryStream(); 

     FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read); 

     byte[] bytes = new byte[file.Length]; 

     file.Read(bytes, 0, (int)file.Length); 

     memoryStream.Write(bytes, 0, (int)file.Length); 

     file.Close(); 

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

     httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 

     httpResponseMessage.StatusCode = HttpStatusCode.OK; 

     return httpResponseMessage; 
    } 
} 

上面的代碼工作正常,但我們處理的一些文件可能是2 GB或更大,導致連接超時。過去,我們使用類似於下面的代碼(使用HttpHandlers)將響應組塊化爲響應流,以保持連接的成功。

byte[] b = new byte[this.BufferChunkSize]; 
int byteCountRead = 0; 

while ((byteCountRead = stream.Read(b, 0, b.Length)) > 0) 
{ 
    if (!response.IsClientConnected) break; 

    response.OutputStream.Write(b, 0, byteCountRead); 
    response.Flush(); 
} 

我們如何使用前面顯示的新WebAPI編程模型的類似技術?

預先感謝您

回答

26

是的,你可以使用PushStreamContent。如果將它與異步執行(usin,即異步lambdas)結合使用,您可能會得到更有效的結果。

本月早些時候我已經對此方法進行了博客 - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/

該示例使用了一個視頻文件,其原理是相同的 - 將數據的字節推送到客戶端。

+0

@FIllipW¯¯相似 - 首先,非常感謝你的幫助。我沒有使用4.5框架的好處,所以我不能使用4.5框架的內置異步功能。這種方法可以使用4.0框架庫嗎?更具體地說,「WriteToStream」操作將如何改變?我可以只讀取每個字節塊並寫入輸出流而不必擔心異步部分? – raj

+0

Web API中的所有內容都是4.0兼容的。您可以刪除異步/等待並使整個事件同步,或者只需在代碼等待的地方使用continuations(ContinueWith)。 –

+0

@FIllip W - 這對我來說很好。再次感謝您的幫助。我已經接受你的答案。再次感謝 – raj