1. 程式人生 > >sharepoint 列表附件的基本操作

sharepoint 列表附件的基本操作

1)前臺程式碼(Default.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UploadAttachment2._Default" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fileUpload" runat="server" />
        <asp:Label ID="lblOverWrite" runat="server" Text="覆蓋現有檔案"></asp:Label>
        <asp:CheckBox ID="chkOverWrite" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="上傳" onclick="btnUpload_Click" />
        <table>
        <asp:Repeater ID="rptFiles" runat="server" onitemcommand="rptFiles_ItemCommand">
            <HeaderTemplate>
                <tr>
                    <td>編號</td>
                    <td>檔名</td>
                    <td>操作</td>
                </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td><%#Eval("Id") %></td>
                    <td><%#Eval("FileName") %></td>
                    <td>
                      <asp:LinkButton ID="lbtnDel" runat="server" CommandName="del" CommandArgument='<%#Eval("FileName") %>'>刪除</asp:LinkButton>
                    </td>
                </tr>
            </ItemTemplate>
        </asp:Repeater>
        </table>
    </div>
    </form>
</body>
</html>

2)後臺程式碼

a)Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using Microsoft.SharePoint;

namespace UploadAttachment2
{
    public partial class _Default : System.Web.UI.Page
    {
        string allowedExtensions = ConfigurationManager.AppSettings["allowedExtensions"];//允許的檔案格式
        private string webUrl = ConfigurationManager.AppSettings["webUrl"];//網站url
        private string listName = ConfigurationManager.AppSettings["listName"];//列表名稱
        private string filePrefix = "AM_";//檔案字首
        private int id = 1;
        List<Attachment> attachments = new List<Attachment>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindPostedAttachment();
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)//fileUpload包含檔案
            {
                string filePath = fileUpload.FileName;
                string fileExtension = Path.GetExtension(filePath);
                if (IsAllowedExtension(fileExtension))//允許格式
                {
                    long fileContentLenght = fileUpload.FileContent.Length;
                    if (IsAllowedContentLength(fileContentLenght))//檔案2M以下
                    {
                        string fileName = filePrefix+Path.GetFileName(filePath);
                        byte[] fileBytes=fileUpload.FileBytes;
                        if (IsOverWrite())//覆蓋檔案
                        {
                            if (UploadAttachment(fileName, fileBytes, IsOverWrite()))
                            {
                                BindPostedAttachment();
                                Page.ClientScript.RegisterStartupScript(GetType(), "upload_success", "alert('上傳檔案成功!')", true);
                            }
                            else
                            {
                                Page.ClientScript.RegisterStartupScript(GetType(), "upload_failure", "alert('上傳檔案失敗!')", true);
                            }
                        }
                        else
                        {
                            if (!IsExistFile(fileName))//列表不存在fileName附件
                            {
                                if (UploadAttachment(fileName, fileBytes, IsOverWrite()))
                                {
                                    BindPostedAttachment();
                                    Page.ClientScript.RegisterStartupScript(GetType(), "upload_success", "alert('上傳檔案成功!')", true);
                                }
                                else
                                {
                                    Page.ClientScript.RegisterStartupScript(GetType(), "upload_failure", "alert('上傳檔案失敗!')", true);
                                }
                            }
                            else//列表存在fileName附件
                            {
                                Page.ClientScript.RegisterStartupScript(GetType(), "file_is_exist", "alert('檔案已經存在!')", true);
                            }
                        }
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "no_allowed_content_length", "alert('單個檔案大小不能大於2M!')", true);
                    }
                }
                else//不允許格式
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "no_allowed_extension", "alert('上傳檔案格式不正確!')", true);
                }
            }
            else//fileUpload不包含檔案
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "has_no_file", "alert('請選擇上傳檔案!')", true);
            }
        }
        /// <summary>
        /// 繫結上傳的附件
        /// </summary>
        private void BindPostedAttachment()
        {
            GetPostedAttachments();
            rptFiles.DataSource = attachments;
            rptFiles.DataBind();
        }
        /// <summary>
        /// 上傳檔案
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileStream"></param>
        /// <param name="overWrite"></param>
        /// <returns></returns>
        private bool UploadAttachment(string fileName, byte[] fileBytes, bool overWrite)
        {
            bool flag = false;
            SPWeb web = null;
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    web = new SPSite(webUrl).OpenWeb();
                });
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists[listName];
            SPListItem item = list.GetItemById(id);
            if (overWrite)//覆蓋
            {
                try
                {
                    item.Attachments.Recycle(fileName);
                }
                catch (Exception ex)
                { }
            }
            item.Attachments.Add(fileName, fileBytes);
            try
            {
                item.Update();
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            finally {
                web.Dispose();
            }
            return flag;
        }
        /// <summary>
        /// 判斷檔案是否已經存在
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool IsExistFile(string fileName)
        {
            bool flag = false;
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    using (SPWeb web = new SPSite(webUrl).OpenWeb())
                    {
                        SPList list = web.Lists[listName];
                        SPListItem item = list.GetItemById(id);
                        for (int i = 0; i < item.Attachments.Count; i++)
                        {
                            if (item.Attachments[i] == fileName)
                            {
                                flag = true;
                            }
                        }
                    }
                });
            return flag;
        }
        /// <summary>
        /// 獲取所有上傳的附件
        /// </summary>
        private void GetPostedAttachments()
        {
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    using (SPWeb web = new SPSite(webUrl).OpenWeb())
                    {
                        SPList list = web.Lists[listName];
                        SPListItem item = list.GetItemById(id);
                        for (int i = 0; i < item.Attachments.Count; i++)
                        {
                            attachments.Add(new Attachment(i + 1, item.Attachments[i]));
                        }
                    }
                });
        }
        /// <summary>
        /// 上傳檔案是否是可以允許的格式
        /// </summary>
        /// <returns></returns>
        private bool IsAllowedExtension(string fileExtension)
        {
            bool flag = false;
            foreach (string allowedExtension in allowedExtensions.Split(';'))
            {
                if (fileExtension == allowedExtension)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        /// <summary>
        /// 上傳檔案大小是否允許
        /// </summary>
        /// <returns></returns>
        private bool IsAllowedContentLength(long fileContentLenght)
        {
            bool flag = false;
            if (fileContentLenght <= 2 * 1024 * 1024)
            {
                flag = true;
            }
            return flag;
        }
        /// <summary>
        /// 判斷是否覆蓋
        /// </summary>
        /// <returns></returns>
        private bool IsOverWrite()
        {
            bool flag = false;
            if (chkOverWrite.Checked)
            {
                flag = true;
            }
            return flag;
        }
        /// <summary>
        /// 刪除附件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rptFiles_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string fileName=e.CommandArgument.ToString();
                if (DelAttachment(fileName))
                {
                    BindPostedAttachment();
                    Page.ClientScript.RegisterStartupScript(GetType(), "delete_success", "alert('刪除檔案成功!')", true);
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "delete_failure", "alert('刪除檔案失敗!')", true);
                }
            }
        }
        /// <summary>
        /// 刪除附件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool DelAttachment(string fileName)
        {
            bool flag = false;
            SPWeb web = null;
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    web = new SPSite(webUrl).OpenWeb();
                });
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists[listName];
            SPListItem item = list.GetItemById(id);
            item.Attachments.Recycle(fileName);
            try
            {
                item.Update();
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            finally
            {
                web.Dispose();
            }
            return flag;
        }
    }
}

b)Attachment.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UploadAttachment2
{
    public class Attachment
    {
        public Attachment() { }
        public Attachment(int id, string fileName)
        {
            this.Id = id;
            this.FileName = fileName;
        }
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        private string fileName;

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
    }
}