【问题标题】:How limit size of file upload but show a meaningful response?如何限制文件上传的大小但显示有意义的响应?
【发布时间】:2024-04-20 21:00:01
【问题描述】:

我将此添加到我的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

有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    在您的 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");
        }
    
    }
    

    【讨论】:

      最近更新 更多