1.在vs.2005中新建.aspx,
HTML代码如下:
<head id="Head1" runat="server">
<title>多文件上传示例源码</title>
<style type="text/css">
body
{
font-size:12px;
}
aspx_Button
{
background-color:LightSteelBlue;
border-style:solid;
border-width: 1px;
border-color: LightSkyBlue;
}
</style>
</head>
<body>
<form id="attachme" method="post" enctype="multipart/form-data" runat="server">
多文件上传示例<br />
<input id="FindFile" type="file" size="28" runat="server" name="FindFile">
<br>
<asp:ListBox ID="FileList" runat="server" CssClass="txtbox" Height="100px" Width="274px"
SelectionMode="Multiple"></asp:ListBox><br>
<asp:Button ID="AddFile" runat="server" CssClass="aspx_Button" Height="23px" Width="72px"
Text="添加文件" OnClick="AddFile_Click"></asp:Button>
<asp:Button ID="RemvFile" runat="server" CssClass="51aspx_Button" Height="23px" Width="72px"
Text="删除文件" OnClick="RemvFile_Click"></asp:Button>
<input class="51aspx_Button" id="Upload" type="submit" value="上传" runat="server"
onserverclick="Upload_ServerClick" name="Upload">
</form>
<asp:Label ID="TipInfo" runat="server" Height="129px" Width="273px"></asp:Label>
</body>
</html>
2.编写.cs代码,如下:
protected void Page_Load(object sender, EventArgs e)
{
}
static public ArrayList hif = new ArrayList(); // 保存文件列表
public int filesUploaded = 0; // 上传文件的数量
/// <summary>
/// 将要上传的文件添加到listbox中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddFile_Click(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
hif.Add(FindFile);
FileList.Items.Add(FindFile.PostedFile.FileName);
}
else
{}
}
/// <summary>
/// 从listbox中删除指定的文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RemvFile_Click(object sender, EventArgs e)
{
if (FileList.SelectedIndex == -1)
{
TipInfo.Text = "请选中要删除的文件.";
return;
}
else if (FileList.Items.Count != 0)
{
hif.RemoveAt(FileList.SelectedIndex);
FileList.Items.Remove(FileList.SelectedItem.Text);
TipInfo.Text = "";
}
}
/// <summary>
/// 循环上传listbox中的文件到指定的文件夹下
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Upload_ServerClick(object sender, System.EventArgs e)
{
string baseLocation = Server.MapPath("Files/"); // 上传路径
string status = ""; // 上传成功后显示的文件列表
if ((FileList.Items.Count == 0) && (filesUploaded == 0))
{
TipInfo.Text = "请指定要上传的文件.";
return;
}
else
{
foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
{
try
{
string fn = System.IO.Path.GetFileName(HIF.PostedFile.FileName);
HIF.PostedFile.SaveAs(baseLocation + fn);
filesUploaded++;
status += fn + "<br>";
}
catch (Exception err)
{
TipInfo.Text = "对不起,上传失败 " + baseLocation
+ "<br>" + err.ToString();
}
}
if (filesUploaded == hif.Count)
{
TipInfo.Text = "恭喜,您共上传了 " + filesUploaded + " 个文件。 <br>" + status;
}
hif.Clear();
FileList.Items.Clear();
}
}