2012-09-14 41 views
8

我想使用HttpResponse.OutputStream連同ContentResult,以便我可以不時地使用Flush,以避免使用.Net使用太多的RAM。如何在不使用太多RAM的情況下正確地從MVC3中傳輸大數據?

但是所有帶有MVC FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult的示例都顯示了將所有數據存入內存並傳遞給其中一個的代碼。還有一個帖子建議,返回EmptyResult連同使用HttpResponse.OutputStream是不好的主意。我怎麼能在MVC中做到這一點?

什麼是正確的方式來組織從MVC服務器的大數據(HTML或二進制)的可沖刷輸出?

爲什麼返回EmptyResultContentResultFileStreamResult一個壞主意?

+0

有沒有人有關於使用管道流的信息在http://stackoverflow.com/a/2189635/37055中提到 –

回答

5

如果您已經有了一個可以使用的流,那麼您會希望使用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(); 
} 

Here是Microsoft的文章,解釋上面的代碼。

相關問題