在上传文件时限制上传文件的大小,并捕捉超过文件大小限制的异常

在上传文件时,我们可以在web.config里设置允许上传的文件大小。但是,当上传的文件超过设置的限制时,在Application_Error事件里是无法捕捉到这个异常的。下面,就是捕捉上传文件超过设置大小的方法:
首先,在web.config里设置允许一次上传的文件的总大小;

 

[xhtml] view plain copy
  1. Web.config 文件  
  2. <httpRuntime maxRequestLength="400" executionTimeout="3600" appRequestQueueLimit="10000"/>  
 

 

其次,在Global里加入如下的代码:

[c-sharp] view plain copy
  1. <%@ Application Language="C#" %>  
  2. <%@ Import Namespace="System.Web.Configuration" %>  
  3. <mce:script RunAt="server"><!--  
  4.   protected void Application_BeginRequest(object sender, EventArgs e)  
  5.   {  
  6.     //本代码的功能是检查页面请求的大小,如果超过了配置文件maxRequestLength的设定值,就提示用户超过了所允许的文件大小。  
  7.       
  8.       
  9.     //从配置文件里得到配置的允许上传的文件大小  
  10.     HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");  
  11.     //maxRequestLength 为整个页面的大小,不仅仅是上传文件的大小,所以扣除 100KB 的大小,  
  12.     //maxRequestLength单位为KB  
  13.     int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;  
  14.     //当前请求上下文的HttpApplication实例  
  15.     HttpContext context = ((HttpApplication)sender).Context;  
  16.       
  17.     //判断请求的内容长度是否超过了设置的字节数  
  18.     if (context.Request.ContentLength > maxRequestLength)  
  19.     {  
  20.       //得到服务对象  
  21.       IServiceProvider provider = (IServiceProvider)context;  
  22.       HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));  
  23.       //检查请求是否包含正文数据  
  24.       if (workerRequest.HasEntityBody())  
  25.       {          
  26.         //请求正文数据的长度  
  27.         int requestLength = workerRequest.GetTotalEntityBodyLength();  
  28.         //得到加载的初始字节数  
  29.         int initialBytes = 0;  
  30.         if (workerRequest.GetPreloadedEntityBody() != null)  
  31.           initialBytes = workerRequest.GetPreloadedEntityBody().Length;  
  32.           
  33.         //检查是否所有请求数据可用  
  34.         if (!workerRequest.IsEntireEntityBodyIsPreloaded())  
  35.         {  
  36.           byte[] buffer = new byte[512000];   
  37.           //设置要接收的字节数为初始字节数  
  38.           int receivedBytes = initialBytes;  
  39.           //读取数据,并把所有读取的字节数加起来,判断总的大小  
  40.           while (requestLength - receivedBytes >= initialBytes)  
  41.           {  
  42.             //读取下一块字节  
  43.             initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);  
  44.             //更新接收到的字节数  
  45.             receivedBytes += initialBytes;  
  46.           }  
  47.           initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);  
  48.         }  
  49.       }  
  50.       //请求重定向到上载页面,并给用户提示信息。  
  51.       context.Response.Redirect(this.Request.Url.LocalPath + "?error=" + Server.UrlEncode("您上传的文件超过了允许的大小。"));  
  52.     }  
  53.   }  
  54. // --></mce:script>  
 

最后,上传的页面设置如下:

[c-sharp] view plain copy
  1. <%@ Page Language="C#" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <mce:script runat="server"><!--  
  4.   protected void Button1_Click(object sender, EventArgs e)  
  5.   {  
  6.     FileUpload1.SaveAs(Server.MapPath("~") + "//" + System.IO.Path.GetFileName(FileUpload1.FileName));  
  7.     err.Text = "";  
  8.   }  
  9.   protected void Page_Load(object sender, EventArgs e)  
  10.   {  
  11.     if (!String.IsNullOrEmpty(Request.QueryString["error"]))  
  12.     {  
  13.       err.Text = Server.HtmlEncode(Request.QueryString["error"]);  
  14.     }  
  15.   }  
  16. // --></mce:script>  
  17. <html xmlns="http://www.w3.org/1999/xhtml">  
  18. <head runat="server">  
  19.   <title></title>  
  20. </head>  
  21. <body>  
  22.   <form id="form1" runat="server" action="?">  
  23.   <asp:FileUpload ID="FileUpload1" runat="server" />  
  24.   <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上载" />  
  25.   <div><asp:Label ID="err" runat="server" ForeColor="Red"></asp:Label></div>  
  26.   </form>  
  27. </body>  
  28. </html>  
 

 

 

转自孟子E章 - 原文连接http://dotnet.aspx.cc/file/Catch-maxRequestLength-Exceptions-When-Uploading-File-in-ASPNET.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值