ASP.NET使用FileUpload时限制文件大小

2014-07-24 19:01:12|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:C#, ASP.NET|来源:唯设编程网

默认情况,ASP.NET上传文件的最大值为4M,如果我们不做任何处理,等到Application_Error事件处理捕获到“Maximum request length exceeded.”异常为时已晚,页面已无法正常Redirect至Custom Error Page。所以我们应该设法使系统不抛出“Maximum request length exceeded.”异常。而要使系统不抛出该异常,就应在HttpHandler处理Request之前,使HttpHandler得到的HttpContext的内容小于maxRequestLength。我们可以在Global.asax中的Application_BeginRequest事件处理过程中作一番文章

<httpRuntime executionTimeout="300" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>

 private void Application_BeginRequest (Object source, EventArgs e)
 {
     HttpRequest request = HttpContext.Current.Request;
     if (request.ContentLength > 40960000)//4096000 is maxRequestLength
     {
        HttpApplication app = source as HttpApplication;
        HttpContext context = app.Context;

        HttpWorkerRequest wr =
              (HttpWorkerRequest)(context.GetType().GetProperty
              ("WorkerRequest", BindingFlags.Instance |
              BindingFlags.NonPublic).GetValue(context, null));
         byte[] buffer;
         if (wr.HasEntityBody())
         {
             int contentlen = Convert.ToInt32(wr.GetKnownRequestHeader(

              HttpWorkerRequest.HeaderContentLength));
              buffer = wr.GetPreloadedEntityBody();
              int received = buffer.Length;
              int totalrecv = received;
              if (!wr.IsEntireEntityBodyIsPreloaded())
              {
                  //buffer = new byte[65535];
                  buffer = new byte[999999];
                  while (contentlen - totalrecv >= received)
                  {
                      received =wr.ReadEntityBody(buffer,
                                buffer.Length);
                      totalrecv += received;
                   }
                   received =wr.ReadEntityBody(buffer, contentlen - totalrecv);
               }
           }
           //Redirect to custom error page.
           context.Response.Redirect("~/ErrorPage.aspx?ErrorInfo=The upload file exceeded,plese upload a small file again.");
      }
 }

其中显示了Request的ContentLength最大为40960000字节,即40000kb,当大于该值时,将会使用Response的Redirect函数将页面跳转到错误提示页面ErrorPage.aspx。

发表评论0条 】
网友评论(共?条评论)..
ASP.NET使用FileUpload时限制文件大小