【问题标题】:How to properly stream big data from MVC3 without using too much RAM?如何在不使用太多 RAM 的情况下正确地从 MVC3 流式传输大数据?
【发布时间】:2012-09-14 23:14:26
【问题描述】:

我想将HttpResponse.OutputStreamContentResult 一起使用,这样我就可以不时使用Flush 来避免.Net 使用过多的RAM。

但所有使用 MVC FileStreamResult, EmptyResult, FileResult, ActionResult, ContentResult 的示例都显示了将所有数据放入内存并传递给其中之一的代码。还有一篇文章建议返回EmptyResult 和使用HttpResponse.OutputStream 是个坏主意。在 MVC 中我还能如何做到这一点?

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

为什么返回 EmptyResultContentResultFileStreamResult 是个坏主意?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 model-view-controller stream ram


【解决方案1】:

如果你已经有一个流可以使用,你会想要使用 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 是解释上述代码的微软文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2013-07-31
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多