問題描述
對于我正在開發(fā)的應(yīng)用程序,我需要允許用戶通過我們的網(wǎng)站上傳非常大的文件(即可能有很多千兆字節(jié)).不幸的是,ASP.NET MVC 似乎在開始為它提供服務(wù)之前將整個請求加載到 RAM 中——對于這樣的應(yīng)用程序來說并不完全理想.值得注意的是,試圖通過如下代碼來規(guī)避這個問題:
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);
}
}
}
未能規(guī)避將請求緩沖到 RAM 的心態(tài).有沒有一種簡單的方法可以解決此問題?
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;
前者在整個請求流中確定內(nèi)容長度;后者僅檢查 Content-Length
標(biāo)頭,它只要求標(biāo)頭已完整發(fā)送.這允許 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.
這篇關(guān)于將大文件上傳到 ASP.NET MVC的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!