代码如下:
Page_Load方法
cblattCase.Items.Clear(); for (int i = 0; i < item.Attachments.Count; i++) { cblattCase.Items.Add(new ListItem("<a href='" + GetSPListItemAttachmentUrl(item, i) + "' target='_black'>" + item.Attachments[i] + "<a>", i.ToString())); }
附件添加及删除
/// <summary> /// 添加附件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnUploadCase_OnClick(object sender, EventArgs e) { string id = Request["id"]; if (id == null) { ShowErr("请先保存草稿"); return; } if (fudCase.FileBytes.Length == 0) { ShowErr("请先选择上传文件"); return; } //SPList list = SPContext.Current.Web.Lists["servicerequest"]; SPListItem item = null; //case附件删除 item = list.Items.GetItemById(int.Parse(Request["id"])); //case附件上传 for (int i = 0; i < item.Attachments.Count; i++) { if (fudCase.FileName == item.Attachments[i]) { ShowErr("文件名重复!"); return; } } item.Attachments.Add(fudCase.FileName, fudCase.FileBytes); item.Update(); //刷新控件 cblattCase.Items.Clear(); for (int i = 0; i < item.Attachments.Count; i++) { cblattCase.Items.Add(new ListItem("<a href='" + GetSPListItemAttachmentUrl(item, i) + "' target='_black'>" + item.Attachments[i] + "<a>", i.ToString())); } } public static string GetSPListItemAttachmentUrl(SPListItem item, int index) { return item.Attachments.UrlPrefix + item.Attachments[index]; } /// <summary> /// 删除附件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnDelCase_OnClick(object sender, EventArgs e) { if (id == null) { ShowErr("请先保存草稿"); return; } SPListItem item = null; //case附件删除 item = list.Items.GetItemById(int.Parse(Request["id"])); List<string> attName = new List<string>(); if (item.Attachments.Count > 0) { int tmpIndex = 0; foreach (ListItem lItem in cblattCase.Items) { if (lItem.Selected) { attName.Add(item.Attachments[tmpIndex]); } tmpIndex++; } for (int i = 0; i < attName.Count; i++) { item.Attachments.Delete(attName[i]); } item.Update(); } //刷新控件 cblattCase.Items.Clear(); for (int i = 0; i < item.Attachments.Count; i++) { cblattCase.Items.Add(new ListItem("<a href='" + GetSPListItemAttachmentUrl(item, i) + "' target='_black'>" + item.Attachments[i] + "<a>", item.Attachments[i])); } }
前端代码:
<tr> <td class="padding" colspan="6" height="30"> <asp:FileUpload ID="fudCase" runat="server" CssClass="textboxCss1" width="500"/> <asp:Button ID="btnUploadCase" runat="server" Text="上传附件" OnClick="btnUploadCase_OnClick" CssClass="textboxCss1" /> <asp:Button ID="btnDelCase" runat="server" Text="删除附件" OnClick="btnDelCase_OnClick" CssClass="textboxCss1" /> </td> </tr> <tr> <td style="padding:8px;" colspan="3"> <asp:CheckBoxList ID="cblattCase" runat="server" AutoPostBack="false"></asp:CheckBoxList> </td> </tr>