aspx 中轻松实现文件上传
在aspx中实现文件上传是非常容易的,如下代码:
private string upLoadFile(System.Web.UI.HtmlControls.HtmlInputFile tFile,string FilePath)
{
if(tFile.PostedFile.ContentLength>0 )
{
string strFileName = Path.GetFileName(tFile.PostedFile.FileName);
tFile.PostedFile.SaveAs(FilePath + strFileName) ;
return strFileName;
}else{
return "";
}
}
但是有一个问题,如果你的附件大小超过4m那么上传文件会报错,为什么会报错?原因是aspx默认的maxRequestLength 的大小为4096KB也就是4MB,我们需要在Web.config更改如下设置,当然具体的数值根据实际情况来定。
<system.web>
...
<httpRuntime
executionTimeout="300"
maxRequestLength="40960"
useFullyQualifiedRedirectUrl="false"
/>
...
</system.web>
executionTimeout 单位秒
maxRequestLength 单位KB
如何读取maxRequestLenght
.net1.1
static public string getMaxlengthByAppSetting()
...{
//先在Web.Config文件中增加一个key ****************************************//
// <appSettings>
// <add key="maxRequestLength" value="1550000"/>
//</appSettings>
//再来读取这个值,遗憾的是,这样只能写两遍,即
//<system.web>
//<httpRuntime maxRequestLength="1550000" executionTimeout="3600"/>
//</system.web>
//这两个值必须保持一致。
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
return config.AppSettings.Settings["maxRequestLength"].Value;
/**//* *********************以下为修改某个AppSettings的Key值。
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyAppKey"] == null)
config.AppSettings.Settings.Add("MyAppKey", "Hello!");
else
config.AppSettings.Settings["MyAppKey"].Value = "Hello2!";
config.Save();
*/
}
在web.config中添加httpRuntime元素,如下:
<configuration>
<system.web>
<httpRuntime maxRequestLength=8192
useFullyQualifiedRedirectUrl=true
executionTimeout=45
versionHeader=1.1.4128/>
</system.web>
</configuration>
其中maxRequestLength属性就是限制上传大小的,如设为8192即为8M。