Streaming large file uploads to ASP.NET MVC(将大文件上传到 ASP.NET MVC)
问题描述
对于我正在开发的应用程序,我需要允许用户通过我们的网站上传非常大的文件(即可能有很多千兆字节).不幸的是,ASP.NET MVC 似乎在开始为它提供服务之前将整个请求加载到 RAM 中——对于这样的应用程序来说并不完全理想.值得注意的是,试图通过如下代码来规避这个问题:
For an application I'm working on, I need to allow the user to upload very large files--i.e., potentially many gigabytes--via our website. Unfortunately, ASP.NET MVC appears to load the entire request into RAM before beginning to service it--not exactly ideal for such an application. Notably, trying to circumvent the issue via code such as the following:
if (request.Method == "POST")
{
request.ContentLength = clientRequest.InputStream.Length;
var rgbBody = new byte[32768];
using (var requestStream = request.GetRequestStream())
{
int cbRead;
while ((cbRead = clientRequest.InputStream.Read(rgbBody, 0, rgbBody.Length)) > 0)
{
fileStream.Write(rgbBody, 0, cbRead);
}
}
}
未能规避将请求缓冲到 RAM 的心态.有没有一种简单的方法可以解决此问题?
fails to circumvent the buffer-the-request-into-RAM mentality. Is there an easy way to work around this behavior?
推荐答案
原来我的初始代码基本正确;唯一需要改变的就是改变
It turns out that my initial code was basically correct; the only change required was to change
request.ContentLength = clientRequest.InputStream.Length;
到
request.ContentLength = clientRequest.ContentLength;
前者在整个请求流中确定内容长度;后者仅检查 Content-Length 标头,它只要求标头已完整发送.这允许 IIS 几乎立即开始流式传输请求,从而完全消除了最初的问题.
The former streams in the entire request to determine the content length; the latter merely checks the Content-Length header, which only requires that the headers have been sent in full. This allows IIS to begin streaming the request almost immediately, which completely eliminates the original problem.
这篇关于将大文件上传到 ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将大文件上传到 ASP.NET MVC
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
