asp.net - 防止在 ASP.NET 4.0 中上传大文件

标签 asp.net iis-7 file-upload httprequest httpmodule

我们想限制我们网站上的最大上传文件大小。我们已经在 web.config 中设置了适当的限制。我们遇到的问题是,如果上传了一个非常大的文件(例如 1 GB),则在生成服务器端错误之前上传了整个文件,并且错误的类型是不同的文件是巨大的还是不是。

有没有办法在实际上传之前检测待上传文件的大小?

这是我将请求限制为 16 MB 的相关 web.config 设置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="12288"/>
    </system.web>

    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="12582912"/>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

我尝试创建一个 HTTP 模块,这样我就可以在请求生命周期的早期拦截请求,但上传似乎甚至在 BeginRequest 之前就已经发生了。 HttpApplication的事件:
public class UploadModule : IHttpModule
{
    private const int MaxUploadSize = 12582912;

    public void Init(HttpApplication context)
    {
        context.BeginRequest += handleBeginRequest;
    }

    public void Dispose()
    {
    }

    private void handleBeginRequest(object sender, EventArgs e)
    {
        // The upload takes place before this method gets called.

        var app = sender as HttpApplication;

        if (app.Request.Files.OfType<HttpPostedFile>()
            .Any(f => f.ContentLength > MaxUploadSize))
        {
            app.Response.StatusCode = 413;
            app.Response.StatusDescription = "Request Entity Too Large";
            app.Response.End();
            app.CompleteRequest();
        }
    }
}

更新:

我知道像 Flash 这样的客户端技术可以在上传之前检测文件大小,但我们需要一个服务器端的解决方法,因为我们想要针对不支持 Flash/Java/ActiveX/Silverlight 的平台。我相信 IIS 或 ASP.NET 有一个错误,允许上传大文件,尽管有限制,所以我提交了一个错误 here .

与 HTTP 模块和处理程序相比,ISAPI 扩展是否可以让我更好地控制请求处理,例如如果 Content-Length header 被视为大于允许的限制,则允许我中止上传?

更新 2:

叹。 Microsoft 已经关闭了我作为副本提交的错误,但没有提供其他信息。希望他们不只是在这件事上丢球。

更新 3:

万岁!据微软称:

This bug is being resolved as it has been ported over to the IIS product team. The IIS team has since fixed the bug, which will be included in future release of Windows.

最佳答案

问题是上传是使用 HTTP Post 请求一次性发生的,所以您只能在完成后检测到它。

如果您想对此进行更多控制,您应该尝试基于 Flash 的上传小部件,该小部件具有此功能以及更多功能。查看此链接 http://www.ajaxline.com/10-most-interesting-upload-widgets

关于asp.net - 防止在 ASP.NET 4.0 中上传大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4017941/

相关文章:

asp.net - ASCX 控件 ASP.NET - 找不到可见方法

swift - Vapor 将文件上传到 DerivedData 而不是项目结构中的 Public 文件夹

php - 在Facebook App上传图片

Javascript DOM 鼠标事件不适用于 IE 和 Mozilla

javascript - 在 jQuery timeago.js 中本地化字符串

c# - 将成员(member)服务应用到远程 sql 服务器

asp.net - 在asp.net中设置gzip压缩

windows-7 - Windows 7 中的 SMTP 本地服务器? (运行 IIS7)

iis-7 - 监控 IIS7 工作进程的 CPU 使用率

c# - 在 IIS 中重新启动应用程序池时立即运行 Application_Start