浏览附件上传 显示在右边的ListBox中,可以通过删除将对应项删除
<tr>
<td align="right" style="width: 100px" valign="top">
附件:
</td>
<td style="width: 320px" valign="top">
<asp:FileUpload ID="Uploader" runat="server" />
</td>
<td style="width: 100px" valign="top">
<asp:Button ID="UploadButton" runat="server" Text="添加 >" Width="60px" OnClick="UploadButton_Click" />
<br />
<asp:Button ID="DeleteButton" runat="server" Text="< 删除" Width="60px" OnClick="DeleteButton_Click" />
</td>
<td>
<asp:ListBox ID="Attachment" runat="server" Rows="5"></asp:ListBox>
</td>
</tr>
/// <summary>
/// 附件列表(文件名, 文件路径)
/// </summary>
private Dictionary<string, string> Attachments
{
get
{
if (ViewState["Attachments"] == null)
{
ViewState["Attachments"] = new Dictionary<string, string>();
}
return (Dictionary<string, string>)ViewState["Attachments"];
}
set
{
ViewState["Attachments"] = value;
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (!Uploader.HasFile)
{
MessageBox.Show("请选取有效的附件文件!");
return;
}
//文件夹
if (!Directory.Exists(Global.UploadPath))
{
Directory.CreateDirectory(Global.UploadPath);
}
//文件名
string fileName = Path.GetFileName(Uploader.PostedFile.FileName);
string fullFileName = Global.UploadPath + "\\" + fileName;
if (File.Exists(fullFileName))
{
File.Delete(fullFileName);
}
//保存文件
try
{
Uploader.PostedFile.SaveAs(fullFileName);
}
catch (Exception error)
{
MessageBox.Show("保存附件文件失败!" + error.Message);
return;
}
//附件列表登记
if (!Attachments.ContainsKey(fileName))
{
Attachments.Add(fileName, fullFileName);
}
//刷新
this.RefreshAttachment();
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
if (Attachment.SelectedIndex < 0)
{
MessageBox.Show("请选取要删除的附件!");
return;
}
//删除文件
try
{
File.Delete(Attachment.SelectedValue);
}
catch
{
}
//删除附件列表登记
if (Attachments.ContainsKey(Attachment.SelectedItem.Text))
{
Attachments.Remove(Attachment.SelectedItem.Text);
}
Attachment.ClearSelection();
//刷新
this.RefreshAttachment();
}
/// <summary>
/// 刷新附件
/// </summary>
private void RefreshAttachment()
{
Attachment.Items.Clear();
foreach (string key in Attachments.Keys)
{
Attachment.Items.Add(new ListItem(key, Attachments[key]));
}
}
StringBuilder attachment = new StringBuilder();
foreach (ListItem attachmentItem in Attachment.Items)
{
attachment.AppendFormat("{0}|", attachmentItem.Value);
}