捕捉asp.net上传超过文件大小限制的异常
2015-06-01 18:11
771 查看
在上传文件时,我们可以在web.config里设置允许上传的文件大小。但是,当上传的文件超过设置的限制时,在Application_Error事件里是无法捕捉到这个异常的。下面,就是捕捉上传文件超过设置大小的方法:
首先,在web.config里设置允许一次上传的文件的总大小;
Web.config 文件
<httpRuntime maxRequestLength="400" executionTimeout="3600" appRequestQueueLimit="10000"/>
其次,在Global里加入如下的代码:
C# 代码
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script RunAt="server">
protected void Application_BeginRequest(object sender,
EventArgs e)
{
//本代码的功能是检查页面请求的大小,如果超过了配置文件maxRequestLength的设定值,就提示用户超过了所允许的文件大小。
//从配置文件里得到配置的允许上传的文件大小
HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
//maxRequestLength 为整个页面的大小,不仅仅是上传文件的大小,所以扣除 100KB 的大小,
//maxRequestLength单位为KB
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;
//当前请求上下文的HttpApplication实例
HttpContext context = ((HttpApplication)sender).Context;
//判断请求的内容长度是否超过了设置的字节数
if (context.Request.ContentLength > maxRequestLength)
{
//得到服务对象
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
//检查请求是否包含正文数据
if (workerRequest.HasEntityBody())
{
//请求正文数据的长度
int requestLength = workerRequest.GetTotalEntityBodyLength();
//得到加载的初始字节数
int initialBytes = 0;
if (workerRequest.GetPreloadedEntityBody() != null)
initialBytes = workerRequest.GetPreloadedEntityBody().Length;
//检查是否所有请求数据可用
if (!workerRequest.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
//设置要接收的字节数为初始字节数
int receivedBytes = initialBytes;
//读取数据,并把所有读取的字节数加起来,判断总的大小
while (requestLength - receivedBytes >= initialBytes)
{
//读取下一块字节
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);
//更新接收到的字节数
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
//请求重定向到上载页面,并给用户提示信息。
context.Response.Redirect(this.Request.Url.LocalPath + "?error=" + Server.UrlEncode("您上传的文件超过了允许的大小。"));
}
}
</script>
最后,上传的页面设置如下:
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("~") + "\\" + System.IO.Path.GetFileName(FileUpload1.FileName));
err.Text = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Request.QueryString["error"]))
{
err.Text = Server.HtmlEncode(Request.QueryString["error"]);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" action="?">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上载" />
<div><asp:Label ID="err" runat="server" ForeColor="Red"></asp:Label></div>
</form>
</body>
</html>
在上传文件时,我们可以在web.config里设置允许上传的文件大小。但是,当上传的文件超过设置的限制时,在Application_Error事件里是无法捕捉到这个异常的。下面,就是捕捉上传文件超过设置大小的方法:
首先,在web.config里设置允许一次上传的文件的总大小;
Web.config 文件
<httpRuntime maxRequestLength="400" executionTimeout="3600" appRequestQueueLimit="10000"/>
其次,在Global里加入如下的代码:
C# 代码
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script RunAt="server">
protected void Application_BeginRequest(object sender,
EventArgs e)
{
//本代码的功能是检查页面请求的大小,如果超过了配置文件maxRequestLength的设定值,就提示用户超过了所允许的文件大小。
//从配置文件里得到配置的允许上传的文件大小
HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
//maxRequestLength 为整个页面的大小,不仅仅是上传文件的大小,所以扣除 100KB 的大小,
//maxRequestLength单位为KB
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;
//当前请求上下文的HttpApplication实例
HttpContext context = ((HttpApplication)sender).Context;
//判断请求的内容长度是否超过了设置的字节数
if (context.Request.ContentLength > maxRequestLength)
{
//得到服务对象
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
//检查请求是否包含正文数据
if (workerRequest.HasEntityBody())
{
//请求正文数据的长度
int requestLength = workerRequest.GetTotalEntityBodyLength();
//得到加载的初始字节数
int initialBytes = 0;
if (workerRequest.GetPreloadedEntityBody() != null)
initialBytes = workerRequest.GetPreloadedEntityBody().Length;
//检查是否所有请求数据可用
if (!workerRequest.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
//设置要接收的字节数为初始字节数
int receivedBytes = initialBytes;
//读取数据,并把所有读取的字节数加起来,判断总的大小
while (requestLength - receivedBytes >= initialBytes)
{
//读取下一块字节
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);
//更新接收到的字节数
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
//请求重定向到上载页面,并给用户提示信息。
context.Response.Redirect(this.Request.Url.LocalPath + "?error=" + Server.UrlEncode("您上传的文件超过了允许的大小。"));
}
}
</script>
最后,上传的页面设置如下:
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("~") + "\\" + System.IO.Path.GetFileName(FileUpload1.FileName));
err.Text = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Request.QueryString["error"]))
{
err.Text = Server.HtmlEncode(Request.QueryString["error"]);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" action="?">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上载" />
<div><asp:Label ID="err" runat="server" ForeColor="Red"></asp:Label></div>
</form>
</body>
</html>
相关文章推荐
- ASP.NET 上传控件 “Maximum request length exceeded” 异常
- ASP.NET多个按钮同一事件 不同处理
- asp.net 分页类
- 利用JasperReport+iReport进行Web报表开发
- [Asp.net 5] Localization-简单易用的本地化
- [Asp.net 5] Localization-Asp.net运行时多语言
- ASP.NET在IE9,IE10,IE11中Form表单身份验证失效问题解决方法
- 关于Aspose对于Word操作的一些扩展及思考
- 对ASP.NET Cookie的一些新的认识
- asp.net使用chart控件简单制作柱状体、饼图总结
- asp.net 读写配置文件Web.Config
- asp.net 登陆验证 Form表单验证的3种方式 FormsAuthentication.SetAuthCookie;FormsAuthentication.RedirectFromLoginPage;FormsAuthenticationTicket
- asp.net session共享(通过StateServer方式)
- [转]asp.net URL中包含中文参数造成乱码的解决方法
- Asp.net框架
- 如何安装 Google coder for Raspberry Pi
- asp.net mvc重写404,500错误
- 解读ASP.NET 5 & MVC6系列(15):MvcOptions配置
- 解读ASP.NET 5 & MVC6系列(14):View Component
- 解读ASP.NET 5 & MVC6系列(15):MvcOptions配置