我想将 HttpResponse.OutputStream
与 ContentResult
一起使用,这样我就可以不时 Flush
以避免使用太多.Net 的 RAM。
但是 MVC FileStreamResult、EmptyResult、FileResult、ActionResult、ContentResult
的所有示例都显示将所有数据获取到内存并传递到其中之一的代码。另外一篇文章建议返回 EmptyResult
并使用 HttpResponse.OutputStream
是个坏主意。我还能如何在 MVC 中做到这一点?
从 MVC 服务器组织大数据(html 或二进制)的可刷新输出的正确方法是什么?
为什么返回 EmptyResult
或 ContentResult
或 FileStreamResult
是一个坏主意?
最佳答案
如果您已经有一个要使用的流,您可能会想要使用 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/