HttpFileCollection 多文件上传的实现以及需要注意的事项

.aspx 页面中的javascript代码


function addFile() 

      var str = '<br /><INPUT type="file" size="50" runat="server" NAME="File">' ;
      document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str);

}

.aspx 页面中的HTML代码


<P id="MyFile">

   <INPUT type="file" runat="server" size="50" NAME="File" />

</P>
<input type="button" value="增加文件控件" onclick="addFile()"  />

.aspx.cs 中的部分代码


HttpFileCollection uploadFileList= HttpContext.Current.Request.Files;

for (int i = 0; i < uploadFileList.Count; i++)
{
   if (uploadFileList[i].FileName!="")
   {

      string str=uploadFileList[i].FileName;

      string newfilename="test";
      string newfilepath = Server.MapPath("") + "//" + newfilename + str.Substring(str.LastIndexOf("."));
      uploadFileList[i].SaveAs(newfilepath);
    }
}

需要注意的是 :

1)需要在 file 控件中加入  runat="server",否则不能被HttpContext.Current.Request.Files取到

2)若出现"Cannot access a closed file" 错误信息,则需要在web.config中配置如下信息:

<system.web>

  <httpRuntime maxRequestLength="819200" requestLengthDiskThreshold="819200" />

</system.web>

原文地址:https://www.cnblogs.com/abccome/p/3344608.html