asp.net-mvc - 如何在不使用太多 RAM 的情况下正确地从 MVC3 传输大数据?

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

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

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

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

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

最佳答案

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

关于asp.net-mvc - 如何在不使用太多 RAM 的情况下正确地从 MVC3 传输大数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433132/

相关文章:

php - Laravel5 (PHP) 还是 SailsJS (node.js)?

c# - 如何在 ASP.NET MVC 中选择表行

c# - 具有键 'XXX' 的 ViewData 项的类型为 'System.Int32' 但必须为 'IEnumerable<SelectListItem>' 类型

c# - 无法在 MVC 3 中使用 VAR 字符串添加多个 html 类

c# - Fluent nHibernate映射问题

c++ - 将遗留 C 代码重构为 MVC 设计

java - MVC 将整个模型或事件发送到 View

asp.net-mvc - ASP MVC 与 Ruby on Rails

c# - MVC/实体代码优先的多个上下文,它们之间具有参照完整性

asp.net-mvc - 使用MVC3 WebGrid帮助器将连字符添加到html属性名称