如何在不使用太多RAM的情况下正确地从MVC3流式传输大数据?

alp*_*pav 10 model-view-controller asp.net-mvc ram stream asp.net-mvc-3

我想和我HttpResponse.OutputStream一起使用,ContentResult以便我可以Flush不时地避免使用.Net过多的RAM.

但是MVC的所有示例都FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult显示了将所有数据存入内存并传递给其中一个的代码.另外一篇文章表明,EmptyResult与使用一起回归HttpResponse.OutputStream是个坏主意.我怎么能在MVC中做到这一点?

从MVC服务器组织大数据(html或二进制)的可刷新输出的正确方法是什么?

为什么回国EmptyResult或者ContentResult还是FileStreamResult一个坏主意?

Cha*_*tch 6

如果您已经有一个要使用的流,您可能希望使用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();
}
Run Code Online (Sandbox Code Playgroud)

是解释上述代码的微软文章.