asp.net(C#)多文件上传(源代码)vs2008
1.新建“项目”MutiFileUpload。如图所示:
2.Default.aspx如下图所示的设计。
3。Default.aspx.cs文件代码如下所示:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace MutiFileUpload
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int FileNum = 0;
string filepath = Server.MapPath("./") + "UploadFile";
string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hfc[i].ContentLength > 0)
{
hpf.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
FileNum++;
//uploadFiles.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
}
else
{
Response.Write("<script>alert('请选择你要上传的文件!')</script>");
//跳出for循环
i = hfc.Count;
break;
}
}
Response.Write("<script>alert('上传成功!')</script>");
Response.Write("共上传成功的文件个数为:" + FileNum + "个");
FileNum = null;
}
}
}
4。如果你想添加多个文件,直接添加fileupload控件就是了,后台的代码不用修改,不会影响的,后台代码会自动识别有几个要上传的文件。