如何限制asp.net中上传文件的大小的代码


在web.config中控制上传文件大小的地方:
复制代码 代码如下:

<system.web><httpRuntime executionTimeout="9999" maxRequestLength="2097151"/></system.web>

maxRequestLength是控制上传大小得参数请求的最大大小(以千字节为单位)。默认大小为 4096 KB (4 MB)。ExecutionTimeout 指示在请求被 ASP.NET 自动关闭前允许执行的最大秒数。默认值为 90 秒。单位是秒。详细大家可以看Msdn。

http://msdn.microsoft.com/zh-cn/library/system.web.configuration.httpruntimesection.maxrequestlength%28v=VS.80%29.aspx

解决asp.net上传文件大小限制
对于asp.net,默认只允许上传2m文件,增加如下配置,一般可以自定义最大文件大小.

<httpruntime executimaxrequestlength="40960" usefullyqualifiedredirecturl="false"/>

如果还不行,可以使用思归提供的方案:

我们在上传大文件时都遇到过这样或那样的问题。设置很大的maxrequestlength值并不能完全解决问题,因为asp.net会block直到把整个文件载入内存后,再加以处理。实际上,如果文件很大的话,我们经常会见到internet explorer显示 "the page cannot be displayed - cannot find server or dns error",好像是怎么也catch不了这个错误。为什么?因为这是个client side错误,server side端的applicati

handling server error when upload file too large

解决的方法是利用隐含的httpworkerrequest,用它的getpreloadedentitybody 和 readentitybody方法从iis为asp.net建立的pipe里分块读取数据
复制代码 代码如下:

iserviceprovider provider = (iserviceprovider) httpcontext.current;
httpworkerrequest wr = (httpworkerrequest) provider.getservice(typeof(httpworkerrequest));
byte[] bs = wr.getpreloadedentitybody();
....
if (!wr.isentireentitybodyispreloaded())
{
int n = 1024;
byte[] bs2 = new byte[n];
while (wr.readentitybody(bs2,n) >0)
{
.....
}
}

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3