添加一个上载文件控件和两个Button控件
int nParentID=-1;
protected void Page_Load(object sender,EventArgs e)
{//获取参数DirID的值
if(Request.Params["DirID"]!=null)
{
if(Int32.TryParse(Request.Params["DirID"].ToString(),out nDirID)==false){return;}
}
SureBtn.Enabled=nParentID<=-1?false:true;
}
函数UploadFiles(int nParentID)的具体步骤如下:
(1)从HttpContext的当前上下文的Request对象中获取所有文件,并用列表fileList保存。
(2)获取fileList中每一个文件,表示为hPostedFile.
(3)获取文件的名称,并把文件保存到硬盘上。
(4)把已经上传的文件信息保存到数据库中。
(5)在页面上显示已经上传的文件信息。
private void UploadFiles(int nParentID)
{
HttpFileCollection fileList=HttpContext.Current.Request.Files; //获取上传文件的列表
StringBuilder uploadMsg=new StringBuilder("上载的文件如下:"+"<br>");//定义显示的消息
IDisk disk=new Disk();
try
{//上载文件列表中的每一个文件
for(Int i=0;i<fileList.Count;i++)
{
HttpPostedFile hPostedFile=fileList[i];
string fileName;
//获取上传文件的文件名称
fileName=Path.GetFileName(hPostedFile.FileName);
if(fileName!=null)
{//上载文件
hPostedFile.SaveAs(MapPath("WebDisk/")+fileName);
//添加文件到数据库中
disk.AddFile(fileName.nParentID,hPostedFile.ContentLength,"WebDisk/"+fileName,hPostedFile.ContentType);
uploadMsg.Append("文件名称:"+fileName+"<br>");
}
//显示上载的文件操作成功信息
StatusMsg.Text=uploadMsg.ToString();
}
catch(Excepton ex)
{
StatusMsg.Text=ex.Message;
}
}
}
protected void SureBtn_Click(object sender,EventArgs e)
{
UploadFiles(nParentID);//上传所有文件
}
//同时上传多个文件
<script language="javascript" type="text/javascript">
function addFile()
{
var filebutton='<br><input type="file" size="50" name="File" class="ButtonCss"/>';
document.getElementById('FileList').insertAdjacentHTML("beforeEnd",filebutton);
}