2007年10月25日星期四

使用HtmlInputFile Control 上传大文件

大家可能都用过HtmlInputFile Control 来上传文件到服务器。你会发现如果上传大文件的话, 会报错。 原因是上传文件的大小默认是4096K。 在web.config.comments 文件中有一个 节点, 内容类似一下:

< executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false" />

这是。NET的默认参数。 大家可以看到“maxRequestLength="4096"”
那么我们可以通过修改这个参数来增大上传文件的大小。 例如 在Web.config文件中加入以下的内容:

[system.web>
[httpruntime maxrequestlength="40960" executiontimeout="100">
[/SYSTEM.WEB>
[/configuration>

* 把[ 换成 < , 没办法, 不给我贴XML格式

可以加入到系统的web.config或虚拟目录下的web.config中。 差别是影响的范围不一样。 注意的是, 如果你增大了maxRequestLength, 同样需要增加executionTimeout, 否则会产生超时报错。


那么我们如何在程序中读出这个变量呢。
在。NET2。0 以下。 你可以通过如下方法:
object section = HttpContext.Current.GetConfig("system.web/httpRuntime");
Type configSection = section.GetType();
if (configSection != null)
{
PropertyInfo pInfo = configSection.GetProperty("MaxRequestLength", BindingFlags.Instance BindingFlags.NonPublic);
if (pInfo != null)
int maxLength = (int)pInfo.GetValue(section,null)
}

在.NET 3.0 中, 提供了HttpRuntimeSection 类, 可以直接访问MaxRequestLength 属性来获取。
// Get the section related object.
HttpRuntimeSection configSection =
(HttpRuntimeSection)config.GetSection("system.web/httpRuntime");

// Get the MaxRequestLength property value.
Response.Write("MaxRequestLength: " +
configSection.MaxRequestLength + "
");

// Set the MaxRequestLength property value to 2048 kilobytes.
configSection.MaxRequestLength = 2048;


参见:

httpRuntime Element (ASP.NET Settings Schema)

ASP.NET HtmlInputFile Control

HttpRuntimeSection Members

1 条评论:

匿名 说...

yeah... thank you for this text :)