aspx 中轻松实现文件上传

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。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值