对于我正在开发的应用程序,我需要允许用户通过我们的网站上传非常大的文件(即可能有很多千兆字节).不幸的是,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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!