使用asp:FileUpLoad控件上传文件时文件太大

时间:2011-07-13 16:27:12

标签: c# .net file-upload webforms

我正在使用asp:FileUpLoad上传asp.net c#项目中的文件。只要文件大小不超过允许的最大值,这一切都可以正常工作。超过最大值时。我收到错误“Internet Explorer cannot display the webpage”。问题是try catch块没有捕获错误,所以我不能给user a friendly message他们已经删除了允许的大小。我在搜索网页时看到过这个问题,但我找不到合适的解决方案。

我会查看其他控件,但我的管理可能不会购买第三方控件。

根据建议ajac的回答,我需要添加此评论。几个月前我试图加载ajax控件。一旦我使用ajax控件,我就会收到此编译错误。

  

错误98类型'System.Web.UI.ScriptControl'在一个中定义   未引用的程序集。您必须添加对程序集的引用   'System.Web.Extensions,Version = 4.0.0.0,Culture = neutral,   公钥= 31bf3856ad364e35' 。

虽然我添加了'System.Web.Extensions',但我可以摆脱它。所以我放弃了Ajax并使用了其他技术。

所以我需要解决这个问题或一个全新的解决方案。

6 个答案:

答案 0 :(得分:30)

  

默认文件大小限制为(4MB),但您可以通过在上载页面所在的目录中删除web.config文件,以本地化方式更改默认限制。这样你就不必让你的整个网站允许大量上传(这样做会让你受到某种攻击)。

只需在<system.web>部分下的web.config中进行设置即可。例如在下面的示例中,我将最大长度设置为2GB

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

请注意,maxRequestLength设置为KB,可以设置为2GB (2079152 KB's)。实际上,我们通常不需要设置2GB请求长度,但如果您将请求长度设置得更高,我们还需要增加executionTimeout

Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)

详情请参阅httpRuntime Element (ASP.NET Settings Schema)

现在,如果您要向用户显示自定义消息,那么文件大小是否大于100MB

你可以这样做..

if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 104857600)
{
    //FileUpload1.PostedFile.ContentLength -- Return the size in bytes
    lblMsg.Text = "You can only upload file up to 100 MB.";
}

答案 1 :(得分:3)

  1. 在客户端,Flash和/或ActiveX和/或Java和/或HTML5文件API是测试文件大小和阻止提交的唯一方法。使用像Uploadify这样的包装器/插件,您不必自己动手,就可以获得跨浏览器解决方案。

  2. 在服务器上,在global.asax中,输入:

    public const string MAXFILESIZEERR = "maxFileSizeErr";
    
    public int MaxRequestLengthInMB
    {
        get
        {
            string key = "MaxRequestLengthInMB";
    
            double maxRequestLengthInKB = 4096; /// This is IIS' default setting 
    
            if (Application.AllKeys.Any(k => k == key) == false)
            {
                var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                if (section != null)
                    maxRequestLengthInKB = section.MaxRequestLength;
    
                Application.Lock();
                Application.Add(key, maxRequestLengthInKB);
                Application.UnLock();
            }
            else
                maxRequestLengthInKB = (double)Application[key];
    
            return Convert.ToInt32(Math.Round(maxRequestLengthInKB / 1024));
        }
    }
    
    void Application_BeginRequest(object sender, EventArgs e)
    {
        HandleMaxRequestExceeded(((HttpApplication)sender).Context);
    }
    
    void HandleMaxRequestExceeded(HttpContext context)
    {
        /// Skip non ASPX requests.
        if (context.Request.Path.ToLowerInvariant().IndexOf(".aspx") < 0 && !context.Request.Path.EndsWith("/"))
            return;
    
        /// Convert folder requests to default doc; 
        /// otherwise, IIS7 chokes on the Server.Transfer.
        if (context.Request.Path.EndsWith("/"))
            context.RewritePath(Request.Path + "default.aspx");
    
        /// Deduct 100 Kb for page content; MaxRequestLengthInMB includes 
        /// page POST bytes, not just the file upload.
        int maxRequestLength = MaxRequestLengthInMB * 1024 * 1024 - (100 * 1024);
    
        if (context.Request.ContentLength > maxRequestLength)
        {
            /// Need to read all bytes from request, otherwise browser will think
            /// tcp error occurred and display "uh oh" screen.
            ReadRequestBody(context);
    
            /// Set flag so page can tailor response.
            context.Items.Add(MAXFILESIZEERR, true);
    
            /// Transfer to original page.
            /// If we don't Transfer (do nothing or Response.Redirect), request
            /// will still throw "Maximum request limit exceeded" exception.
            Server.Transfer(Request.Path);
        }
    }
    
    void ReadRequestBody(HttpContext context)
    {
        var provider = (IServiceProvider)context;
        var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
    
        // Check if body contains data
        if (workerRequest.HasEntityBody())
        {
            // get the total body length
            int requestLength = workerRequest.GetTotalEntityBodyLength();
            // Get the initial bytes loaded
            int initialBytes = 0;
            if (workerRequest.GetPreloadedEntityBody() != null)
                initialBytes = workerRequest.GetPreloadedEntityBody().Length;
            if (!workerRequest.IsEntireEntityBodyIsPreloaded())
            {
                byte[] buffer = new byte[512000];
                // Set the received bytes to initial bytes before start reading
                int receivedBytes = initialBytes;
                while (requestLength - receivedBytes >= initialBytes)
                {
                    // Read another set of bytes
                    initialBytes = workerRequest.ReadEntityBody(buffer,
                        buffer.Length);
    
                    // Update the received bytes
                    receivedBytes += initialBytes;
                }
                initialBytes = workerRequest.ReadEntityBody(buffer,
                    requestLength - receivedBytes);
            }
        }
    }
    

    创建一个您的网页将继承的BasePage类,并将此代码添加到其中:

    public int MaxRequestLengthInMB
    {
        get
        {
            return (Context.ApplicationInstance as Global).MaxRequestLengthInMB;
        }
    }
    
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    
        CheckMaxFileSizeErr();
    }
    
    private void CheckMaxFileSizeErr()
    {
        string key = Global.MAXFILESIZEERR;
        bool isMaxFileSizeErr = (bool)(Context.Items[key] ?? false);
        if (isMaxFileSizeErr)
        {
            string script = String.Format("alert('Max file size exceeded. Uploads are limited to approximately {0} MB.');", MaxRequestLengthInMB);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), key, script, true);
        }
    }
    

    最后,在web.config中,必须将maxAllowedContentLength(以字节为单位)设置为大于maxRequestLength(以kB为单位)。

  3. <system.web>
      <httpRuntime maxRequestLength="32400" />
    </system.web>
    
    <system.webServer>
      <security>
        <requestFiltering>
          <requestLimits maxAllowedContentLength="2000000000" />
        </requestFiltering>
      </security>
    </system.webServer>
    

答案 2 :(得分:2)

事实上,尝试捕获对你没有帮助。但这是一个解决方法:您可以处理Global.asax Application_Error方法中的错误。

示例:

void Application_Error(object sender, EventArgs e) 
{
    // manage the possible 'Maximum Length Exceeded' exception
    HttpContext context = ((HttpApplication)sender).Context;
    /* test the url so that only the upload page leads to my-upload-error-message.aspx in case of problem */
    if (context.Request.Url.PathAndQuery.Contains("mypage"))
        Response.Redirect("/my-upload-error-message.aspx");

}

当然,请注意,如果“mypage”页面上出现任何其他类型的错误,无论发生什么事,您都将被重定向到/my-upload-error-message.aspx。

答案 3 :(得分:1)

您可以尝试使用asp.net工具包上传控件。它是免费的!

http://www.asp.net/ajax/ajaxcontroltoolkit/samples/AsyncFileUpload/AsyncFileUpload.aspx

答案 4 :(得分:0)

这似乎是会话超时的问题,增加会话时间然后再试一次。您可以在web.config文件中设置会话时间

答案 5 :(得分:0)

在您的web.config中,将允许的最大内容长度设置为高于您要接受的内容:

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

然后,在global.asax中,使用Application_BeginRequest设置自己的限制:

  private const int MyMaxContentLength = 10000; //Wathever you want to accept as max file.
  protected void Application_BeginRequest(object sender, EventArgs e)
  {
     if (  Request.HttpMethod == "POST"
        && Request.ContentLength > MyMaxContentLength)
     {
        Response.Redirect ("~/errorFileTooBig.aspx");
     }
  }