将大文件上传到 ASP.NET MVC

Streaming large file uploads to ASP.NET MVC(将大文件上传到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Adding Custom header to the excel file(将自定义标题添加到 excel 文件)
ASP.NET masterpages: how to insert markup in the head section inside the aspx?(ASP.NET 母版页:如何在 aspx 内的 head 部分插入标记?)
Cache-Control Headers in ASP.NET(ASP.NET 中的缓存控制标头)
Could not load file or assembly #39;Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed#39;(无法加载文件或程序集“Newtonsoft.Json,版本=4.5.0.0,文化=中性,PublicKeyToken=30ad4fe6b2a6aeed) - IT屋-程序员软件开
Specifying a custom DateTime format when serializing with Json.Net(使用 Json.Net 序列化时指定自定义 DateTime 格式)