如何限制文件上传的大小,但显示有意义的响应?

时间:2012-10-11 02:35:41

标签: c# asp.net-mvc upload httppostedfilebase

我将此添加到我的web.config文件中:

<httpRuntime maxRequestLength="40960"/> <!-- Limit to 40 megabytes -->

当我尝试上传超过40兆字节的内容时,我会在Firefox中找到它:

The connection was reset

The connection to the server was reset while the page was loading.

  * The site could be temporarily unavailable or too busy. Try again in a few
    moments.
  * If you are unable to load any pages, check your computer's network
    connection.
  * If your computer or network is protected by a firewall or proxy, make sure
    that Firefox is permitted to access the Web.

是否有某种方法可以从内置文件大小限制中受益,但实际上显示了一个不错的错误页面?当然,我可以在控制器中进行此检查,但此时流量已经用完,因为巨大的文件已经到达我的服务器。

if (image.ContentLength > 40960) // 'image' is HttpPostedFileBase

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

你的global.asax.cs怎么样?

void Application_Error(object sender, EventArgs e)
{
    if (Request.TotalBytes > 40960 * 1024)
    {
        Server.ClearError();
        Response.Clear();
        Response.Write("File uploaded is greater than 40 MB");
    }

}