Asp.net-Mvc
如何在不使用太多 RAM 的情況下正確地從 MVC3 流式傳輸大數據?
我想
HttpResponse.OutputStream一起使用,ContentResult這樣我就可以Flush不時避免.Net使用過多的RAM。但是所有使用 MVC 的範例都
FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult顯示了將所有數據放入記憶體並傳遞給其中之一的程式碼。還有一篇文章建議EmptyResult與使用一起返回HttpResponse.OutputStream是個壞主意。我還能如何在 MVC 中做到這一點?從 MVC 伺服器組織大數據(html 或二進制)的可刷新輸出的正確方法是什麼?
為什麼返回
EmptyResultorContentResultorFileStreamResult是個壞主意?
如果您已經有一個流可以使用,您會想要使用 FileStreamResult。很多時候,您可能只能訪問該文件,需要建構一個流,然後將其輸出到客戶端。
System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; // Identify the file to download including its path. string filepath = "DownloadFileName"; // Identify the file name. string filename = System.IO.Path.GetFileName(filepath); try { // Open the file. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer= new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); }這是解釋上述程式碼的微軟文章。