rest api方式實現對文檔庫的管理

寫在前面

剛入職一家新公司,在對接app的時候須要獲取到某公司的sharepoint上面的文檔庫,獲取文檔庫列表,團隊文檔庫中的文件和文件夾列表,我的文檔庫中的文件文件夾列表,及在app端進入文件夾的時候須要獲取該文件夾下的文件及文件夾列表,對文件的上傳下載等操做。html

對rest api的使用,徹底是小白,具體也不知道怎麼實現,在編寫過程當中查找了不少資料,發現這方面的資料極其少,也有多是對本身對這個技術徹底的不瞭解,因此在查找方向上面有問題。最後算是實現了上面的功能,這裏作一下記錄,以及提供一些參考資料。web

實現過程

在若是註冊app以及註冊發佈者的操做步驟,能夠參考我以前的一篇文章:Rest API的簡單應用,這裏介紹瞭如何註冊app和發佈者的操做步驟,也包括瞭如何使用高安全的訪問方式。但願對你有所幫助。項目的簡單描述,本項目實現方式是一個server to server的方式,在app請求iis上面部署的接口,而後該iis服務器再去請求sharepoint服務器的api,獲取文檔庫的相關信息。流程是大概這樣的一個流程。json

註冊的發佈者:全部的操做可使用同一個發佈者。api

團隊文檔庫:可使用同一個ClientID安全

我的文檔庫:每個人對應一個ClientID。服務器

查詢方式使用了OData的方式,關於OData的查詢方式,能夠參考這篇文章app

https://msdn.microsoft.com/zh-SG/library/fp142385ide

查詢post

查詢單個文件的信息ui

 1         /// <summary>
 2         /// 根據文件在服務端的相對url獲取文件信息
 3         /// </summary>
 4         /// <param name="serverRelativeUrl">文件在服務端的相對url</param>
 5         /// <returns>文件信息的json</returns>
 6         public string GetFileInfoByRelativeUrl(string serverRelativeUrl)
 7         {
 8             ///Personal/chenwd/Documents/Shared with Everyone
 9             string queryFileApi = "GetFileByServerRelativeUrl('" + serverRelativeUrl + "')";
10             string filter = "?$select=" + new Document.Core.Model.Document().ToString();
11             if (_documentType == Model.DocumentType.Personal)
12             {
13                 RequestHelper.ClientID = _dicMapping[_userName];
14             }
15             string strFileJson = RequestHelper.RequestGet(_userName, _appUrl, queryFileApi + filter, _documentType);
16             return strFileJson.ToJson("200");
17         }

這裏將文件信息封裝成爲一個類,並重寫了tostring方法,方便操做。

 1    /// <summary>
 2     /// 文檔信息實體類
 3     /// </summary>
 4     public class Document
 5     {
 6         /// <summary>
 7         /// 簽入描述
 8         /// </summary>
 9         public string CheckInComment { get; set; }
10         /// <summary>
11         /// 簽出類型
12         /// </summary>
13         public string CheckOutType { get; set; }
14         /// <summary>
15         /// 內容Tag
16         /// </summary>
17         public string ContentTag { get; set; }
18         /// <summary>
19         /// CustomizedPageStatus
20         /// </summary>
21         public string CustomizedPageStatus { get; set; }
22         /// <summary>
23         /// 獨佔簽出標識
24         /// </summary>
25         public string ETag { get; set; }
26         /// <summary>
27         /// 是否存在
28         /// </summary>
29         public string Exists { get; set; }
30         /// <summary>
31         /// 大小
32         /// </summary>
33         public string Length { get; set; }
34         /// <summary>
35         /// 等級
36         /// </summary>
37         public string Level { get; set; }
38         /// <summary>
39         /// 主要版本
40         /// </summary>
41         public string MajorVersion { get; set; }
42         /// <summary>
43         /// 次版本
44         /// </summary>
45         public string MinorVersion { get; set; }
46         /// <summary>
47         /// 文檔名稱
48         /// </summary>
49         public string Name { get; set; }
50         /// <summary>
51         /// 文檔服務端相對地址
52         /// </summary>
53         public string ServerRelativeUrl { get; set; }
54         /// <summary>
55         /// 建立時間
56         /// </summary>
57         public string TimeCreated { get; set; }
58         /// <summary>
59         /// 最後一次修改時間
60         /// </summary>
61         public string TimeLastModified { get; set; }
62         /// <summary>
63         /// 描述
64         /// </summary>
65         public string Title { get; set; }
66         /// <summary>
67         /// 版本
68         /// </summary>
69         public string UIVersion { get; set; }
70         /// <summary>
71         /// 版本標識
72         /// </summary>
73         public string UIVersionLabel { get; set; }
74         public override string ToString()
75         {
76             Type type = this.GetType();
77             PropertyInfo[] pros = type.GetProperties();
78             string str = string.Empty;
79             foreach (var item in pros)
80             {
81                 str += item.Name + ",";
82             }
83             return str.TrimEnd(',');
84         }
85     }

而後使用Odata查詢,獲取須要的字段的值。
請求輔助類

    /// <summary>
    /// 請求輔助類
    /// </summary>
    public class RequestHelper
    {
        public static string ClientID;
        /// <summary>
        /// get請求
        /// </summary>
        /// <returns></returns>
        public static string RequestGet(string userName, string appUrl, string apiUrl, DocumentType docType)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(appUrl);
            try
            {
                CheckDcomentType(docType);
                var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
                endpointRequest.Method = RequestMethodType.GET.ToString();
                endpointRequest.Accept = "application/json;odata=verbose";
                endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                StreamReader sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8);
                strJson = sr.ReadToEnd();
                sr.Dispose();
            }
            catch (Exception ex)
            {
                strJson = string.Empty.ToErrorJson("500", ex.Message);
            }
            return strJson;
        }
        /// <summary>
        /// 下載文件get請求
        /// </summary>
        /// <param name="appUrl"></param>
        /// <param name="apiUrl"></param>
        /// <param name="filePath"></param>
        /// <param name="fileLength"></param>
        public static void RequestGet(string appUrl, string apiUrl, string filePath, int fileLength, DocumentType docType)
        {
            byte[] buffer = null;
            Uri hostWebUri = new Uri(appUrl);
            CheckDcomentType(docType);
            var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
            endpointRequest.Method = "Get";
            endpointRequest.Accept = "application/json;odata=verbose";
            endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (Stream st = endpointResponse.GetResponseStream())
                {
                    BinaryReader br = new BinaryReader(st);
                    buffer = new byte[fileLength];
                    br.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }
            }
        }
        /// <summary>
        /// 檢測是不是我的文檔庫的請求
        /// </summary>
        /// <param name="docType">文檔類型</param>
        private static void CheckDcomentType(DocumentType docType)
        {
            if (docType == DocumentType.Personal)
            {
                if (string.IsNullOrEmpty(ClientID))
                {
                    throw new ArgumentNullException("ClientID不能爲空");
                }
                else
                {
                    TokenHelper.ClientId = ClientID.ToLower();
                }
            }
        }
        /// <summary>
        /// post請求
        /// </summary>
        /// <returns></returns>
        public static string RequestPost(string userName, string appUrl, string apiUrl, DocumentType docType)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(appUrl);
            try
            {
                CheckDcomentType(docType);
                var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
                endpointRequest.Method = RequestMethodType.POST.ToString();
                endpointRequest.Accept = "application/json;odata=verbose";
                endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                //post請求處理 
                endpointRequest.ContentLength = 0;
                endpointRequest.ContentType = "application/json;odata=verbose";
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                StreamReader sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8);
                strJson = sr.ReadToEnd().ToSuccessJson("200","操做成功");
                sr.Dispose();
            }
            catch (WebException ex)
            {
                strJson = string.Empty.ToErrorJson("500", ex.Message);
            }
            return strJson;
        }
      
        /// <summary>
        /// put請求
        /// </summary>
        /// <returns></returns>
        public static string RequestPut(string userName, string appUrl, string apiUrl, DocumentType docType)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(appUrl);
            try
            {
                CheckDcomentType(docType);
                var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
                endpointRequest.Method = RequestMethodType.PUT.ToString();
                endpointRequest.Accept = "application/json;odata=verbose";
                endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                StreamReader sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8);
                strJson = sr.ReadToEnd();
                sr.Dispose();
            }
            catch (Exception ex)
            {
                strJson = string.Empty.ToErrorJson("500", ex.Message);
            }
            return strJson;
        }
        /// <summary>
        /// delete請求
        /// </summary>
        /// <returns></returns>
        public static string RequestDelete(string userName, string appUrl, string apiUrl, DocumentType docType)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(appUrl);
            try
            {
                CheckDcomentType(docType);
                var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
                endpointRequest.Method = RequestMethodType.DELETE.ToString();
                endpointRequest.Accept = "application/json;odata=verbose";
                endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                StreamReader sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8);
                strJson = sr.ReadToEnd();
                sr.Dispose();
            }
            catch (Exception ex)
            {
                strJson = string.Empty.ToErrorJson("500", ex.Message);
            }
            return strJson;
        }
        /// <summary>
        /// Merge請求
        /// </summary>
        /// <returns></returns>
        public static string RequestMerge(string userName, string appUrl, string apiUrl, DocumentType docType)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(appUrl);
            try
            {
                CheckDcomentType(docType);
                var accessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(appUrl + "/_api/web/" + apiUrl);
                endpointRequest.Method = RequestMethodType.MERGE.ToString();
                endpointRequest.Accept = "application/json;odata=verbose";
                endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                StreamReader sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8);
                strJson = sr.ReadToEnd();
                sr.Dispose();
            }
            catch (Exception ex)
            {
                strJson = string.Empty.ToErrorJson("500", ex.Message);
            }
            return strJson;
        }
    }
RequestHelper

爲string作擴展方法,將結果使用自定義的格式包裹成json格式。

    /// <summary>
    /// string類型擴展
    /// </summary>
    public static class StringExtention
    {
        /// <summary>
        /// 將json數據包裹在code/time/data中
        /// </summary>
        /// <param name="source">json源</param>
        /// <param name="strCode">狀態碼</param>
        /// <returns>json數據</returns>
        public static string ToJson(this string source, string strCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"_code\":");
            sb.Append("\"" + strCode + "\",");
            sb.Append("\"_time\":");
            sb.Append("\"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",");
            sb.Append("\"_data\":");
            sb.Append("{");
            sb.Append("\"files\":");
            sb.Append(source);
            sb.Append("}}");
            return sb.ToString();
        }
        /// <summary>
        ///拼接json字符串
        /// </summary>
        /// <param name="source">FolderJson字符串</param>
        ///  <param name="strCode">是否成功編碼</param>
        /// <param name="strFileInput">要拼接的Filejson字符串</param>
        /// <returns>拼接後的json字符串</returns>
        public static string ToMergeJson(this string source, string strCode, string strFileInput)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"_code\":");
            sb.Append("\"" + strCode + "\",");
            sb.Append("\"_time\":");
            sb.Append("\"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",");
            sb.Append("\"_data\":");
            sb.Append("{");
            sb.Append("\"folders\":");
            if (!string.IsNullOrEmpty(source))
            {
                sb.Append(source);
            }
            else
            {
                sb.Append("{");
                sb.Append("\"d\":");
                sb.Append("{");
                sb.Append("\"results\":");
                sb.Append("[");
                sb.Append("{}]");
                sb.Append("}}");
            }
            sb.Append(",");
            sb.Append("\"files\":");
            sb.Append(strFileInput);
            sb.Append("}}");
            return sb.ToString();
        }
        /// <summary>
        /// 得到下載的文件路徑
        /// </summary>
        /// <param name="source">源json</param>
        /// <param name="strCode">響應碼</param>
        /// <param name="strUrl">下載的url</param>
        /// <returns>下載的url</returns>
        public static string ToDownLoadJson(this string source, string strCode, string strUrl)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"_code\":");
            sb.Append("\"" + strCode + "\",");
            sb.Append("\"_time\":");
            sb.Append("\"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",");
            sb.Append("\"_data\":");
            sb.Append("{");
            sb.Append("\"Url\":");
            sb.Append("\"" + strUrl + "\"");
            sb.Append("}}");
            return sb.ToString();
        }
        /// <summary>
        /// 返回操做成功的json
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="strCode">操做碼</param>
        /// <param name="message">操做提示信息</param>
        /// <returns>json</returns>
        public static string ToSuccessJson(this string source, string strCode, string message)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"_code\":");
            sb.Append("\"" + strCode + "\",");
            sb.Append("\"_time\":");
            sb.Append("\"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",");
            sb.Append("\"_data\":");
            sb.Append("{");
            sb.Append("\"Message\":");
            sb.Append("\"" + message + "\"");
            sb.Append("}}");
            return sb.ToString();
        }
        /// <summary>
        /// 錯誤信息提示
        /// </summary>
        /// <param name="source">源json</param>
        /// <param name="strCode">錯誤碼</param>
        /// <param name="message">錯誤信息</param>
        /// <returns>錯誤信息</returns>
        public static string ToErrorJson(this string source, string strCode, string message)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"_code\":");
            sb.Append("\"" + strCode + "\",");
            sb.Append("\"_time\":");
            sb.Append("\"" + DateTime.Now.ToString("yyyyMMddHHmmss") + "\",");
            sb.Append("\"_data\":");
            sb.Append("{");
            sb.Append("\"Message\":");
            sb.Append("\"" + message + "\"");
            sb.Append("}}");
            return sb.ToString();
        }

    }
StringExtention

查詢某個相對服務端的Url下的全部文件及文件夾

 1         /// <summary>
 2         /// 根據文檔在服務端的相對Url獲取文檔信息
 3         /// </summary>
 4         /// <param name="serverRelativeUrl"></param>
 5         /// <returns></returns>
 6         public string GetDocmumentsByRelativeUrl(string serverRelativeUrl)
 7         {
 8             ///Personal/chenwd/Documents/Shared with Everyone
 9             string queryFileApi = "GetFolderByServerRelativeUrl('" + serverRelativeUrl + "')/Files";
10             string queryFolderApi = "GetFolderByServerRelativeUrl('" + serverRelativeUrl + "')/Folders";
11 
12             string filter = "?$select=" + new Document.Core.Model.Document().ToString();
13             if (_documentType == Model.DocumentType.Personal)
14             {
15                 RequestHelper.ClientID = _dicMapping[_userName];
16             }
17             string strFileJson = RequestHelper.RequestGet(_userName, _appUrl, queryFileApi + filter, _documentType);
18             string strFolderJson = RequestHelper.RequestGet(_userName, _appUrl, queryFolderApi + filter, _documentType);
19             return strFolderJson.ToMergeJson("200", strFileJson);
20         }

根據文檔庫的URL查詢全部的文件及文件夾

 1         /// <summary>
 2         /// 根據url獲取該url下的全部的文檔信息
 3         /// </summary>
 4         /// <param name="docSiteUrl"></param>
 5         /// <returns></returns>
 6         public string GetDocumentsByUrl(string docSiteUrl)
 7         {
 8             //docsiteUrl格式:http://my.xxx.com/Personal/cxxx/Documents/Forms/All.aspx
 9             //解析出文檔庫服務端的相對路徑
10             int startIndex = docSiteUrl.IndexOf("//") + 2;
11             string strRelativeUrl = docSiteUrl.Substring(startIndex);
12             string[] strUrls = strRelativeUrl.Split(new char[] { '/' });
13             strRelativeUrl = "/" + strUrls[1] + "/" + strUrls[2] + "/" + strUrls[3] + "/";
14             string queryFileApi = "GetFolderByServerRelativeUrl('" + strRelativeUrl + "')/Files";
15             string queryFolderApi = "GetFolderByServerRelativeUrl('" + strRelativeUrl + "')/Folders";
16             string filter = "?$select=" + new Document.Core.Model.Document().ToString();
17             if (_documentType == Model.DocumentType.Personal)
18             {
19                 RequestHelper.ClientID = _dicMapping[_userName];
20             }
21             string strFileJson = RequestHelper.RequestGet(_userName, _appUrl, queryFileApi + filter, _documentType);
22             string strFolderJson = RequestHelper.RequestGet(_userName, _appUrl, queryFolderApi + filter, _documentType);
23             return strFolderJson.ToMergeJson("200", strFileJson);
24         }

移動文件

 1         /// <summary>
 2         /// 移動
 3         /// </summary>
 4         /// <param name="serverFileUrl"></param>
 5         /// <param name="newFileUrl"></param>
 6         /// <returns></returns>
 7         public string MoveTo(string serverFileUrl, string newFileUrl)
 8         {
 9             string strMoveToApi = "GetFileByServerRelativeUrl('" + serverFileUrl + "')/moveto(newurl='" + newFileUrl + "',flags=1)";
10 
11             if (_documentType == Model.DocumentType.Personal)
12             {
13                 RequestHelper.ClientID = _dicMapping[_userName];
14             }
15             return RequestHelper.RequestPost(_userName, _appUrl, strMoveToApi, _documentType);
16         }
 1        /// <summary>
 2         /// 建立文件夾
 3         /// </summary>
 4         /// <param name="serverRelativeUrl"></param>
 5         /// <param name="folderName"></param>
 6         /// <returns></returns>
 7         public string CreateFolder(string serverRelativeUrl, string folderName)
 8         {       
 9             serverRelativeUrl = serverRelativeUrl.StartsWith("/", StringComparison.CurrentCulture) ? serverRelativeUrl : "/" + serverRelativeUrl;
10             string createFolderApi = "folders/add('" + serverRelativeUrl + "/" + folderName + "')";
11 
12             if (_documentType == Model.DocumentType.Personal)
13             {
14                 RequestHelper.ClientID = _dicMapping[_userName];
15             }
16             return RequestHelper.RequestPost(_userName, _appUrl, createFolderApi, _documentType);
17         }

將所需的字段封裝爲文檔庫實體,方便之後的操做

 1   /// <summary>
 2     /// 文檔庫實體類
 3     /// </summary>
 4     public class DocumentSite
 5     {
 6         /// <summary>
 7         /// 文檔庫id
 8         /// </summary>
 9         public string Id { set; get; }
10         /// <summary>
11         /// 文檔庫父Url
12         /// </summary>
13         public string ParentWebUrl { set; get; }
14         /// <summary>
15         /// 文檔庫的英文標識名字
16         /// </summary>
17         public string EntityTypeName { set; get; }
18         /// <summary>
19         /// 當前文檔庫文檔數
20         /// </summary>
21         public string ItemCount { set; get; }
22         /// <summary>
23         /// 最後一次刪除時間
24         /// </summary>
25         public string LastItemDeletedDate { set; get; }
26         /// <summary>
27         /// 最後一次修改時間
28         /// </summary>
29         public string LastItemModifiedDate { set; get; }
30         /// <summary>
31         /// 文檔庫名稱
32         /// </summary>
33         public string Title { set; get; }
34         /// <summary>
35         /// 建立時間
36         /// </summary>
37         public string Created { set; get; }
38         /// <summary>
39         /// 返回全部的屬性,以逗號分隔
40         /// </summary>
41         /// <returns></returns>
42         public override string ToString()
43         {
44             Type type = this.GetType();
45             PropertyInfo[] pros = type.GetProperties();
46             string str = string.Empty;
47             foreach (var item in pros)
48             {
49                 str += item.Name + ",";
50             }
51             return str.TrimEnd(',');
52         }
53     }
DocumentSite

根據文檔庫的模板獲取全部的文檔庫列表json

1         /// <summary>
2         /// 得到全部的文檔庫列表
3         /// </summary>
4         /// <returns></returns>
5         public string GetCoworkDocumentSiteList()
6         {
7             string queryApi = "lists?$filter=BaseTemplate eq 101&$select=" + new Document.Core.Model.DocumentSite().ToString();
8             return RequestHelper.RequestGet(_userName, _appUrl, queryApi, _documentType);
9         }

下載:經過api從sharepoint服務器下載文件到iis服務器,而後返回該文件的在iis服務器的相對路徑。固然能夠直接返回byte[],這裏不知道爲何要有該操做也是比較迷惑的地方,api提供的方式徹底能夠返回byte[]

 1        /// <summary>
 2         /// 下載文件
 3         /// </summary>
 4         /// <param name="serverRelativeUrl">文件在服務端的相對路徑</param>
 5         /// <param name="fileLength"></param>
 6         /// <returns></returns>
 7         public string DownLoadFile(string serverRelativeUrl, int fileLength)
 8         {
 9             string loadApi = "GetFileByServerRelativeUrl('" + serverRelativeUrl + "')/openbinarystream";
10             string strJson = string.Empty;
11             try
12             {
13                 string saveServerRelativeUrl = "DownLoad\\" + _userName + "\\";
14                 string filePath = AppDomain.CurrentDomain.BaseDirectory + saveServerRelativeUrl;
15                 string fileName = serverRelativeUrl.Substring(serverRelativeUrl.LastIndexOf('/') + 1);
16                 //"Personal\\chenwd\\Documents\\Shared with Everyone\\SharePoint"
17                 string relativeDir = serverRelativeUrl.Substring(0,
18                     serverRelativeUrl
19                     .LastIndexOf('/'))
20                     .Replace('/', '\\')
21                     .TrimStart("\\".ToCharArray());
22                 filePath = filePath + relativeDir;
23                 if (!Directory.Exists(filePath))
24                 {
25                     Directory.CreateDirectory(filePath);
26                 }
27                 filePath = filePath + "\\" + fileName;
28                 if (_documentType == Model.DocumentType.Personal)
29                 {
30                     RequestHelper.ClientID = _dicMapping[_userName];
31                 }
32                 RequestHelper.RequestGet(_appUrl, loadApi, filePath, fileLength, _documentType);
33                 saveServerRelativeUrl = "\\" + saveServerRelativeUrl + relativeDir + "\\" + fileName;
34                 saveServerRelativeUrl = saveServerRelativeUrl.Replace('\\', '/');
35                 string strFolderJson = string.Empty;
36                 strJson = strFolderJson.ToDownLoadJson("200", saveServerRelativeUrl);
37             }
38             catch (WebException ex)
39             {
40                 strJson = string.Empty.ToErrorJson("500", ex.Message);
41             }
42             return strJson;
43         }

上傳文件是最頭疼的地方,在網上查找了不少方法,最後是如下面的方式操做的。

 1         /// <summary>
 2         /// 上傳文件
 3         /// </summary>
 4         /// <param name="serverReleativeUrl">文件夾的相對路徑</param>
 5         /// <param name="fileName"></param>
 6         /// <returns>返回下載地址</returns>
 7         public string UploadFile(string serverReleativeUrl, string fileName, byte[] data, bool bOverWrite)
 8         {
 9             ClientContext spContext = new ClientContext(_appUrl);
10             //認證方式
11             spContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
12             Web website = spContext.Web;
13             Folder folder = website.GetFolderByServerRelativeUrl(serverReleativeUrl);
14             try
15             {
16                 FileCreationInformation file = new FileCreationInformation();
17                 file.Content = data;
18                 file.Url = fileName;
19                 file.Overwrite = bOverWrite;
20                 folder.Files.Add(file);
21                 spContext.ExecuteQuery();
22             }
23             catch (Exception ex)
24             {
25                 return string.Empty.ToErrorJson("500", ex.Message);
26             }
27             return string.Empty.ToSuccessJson("200", "上傳成功");
28         }

拷貝

1        public string CopyTo(string soureRelativeUrl, string desRelativeUrl) 2  { 3 string strCopyApi = "GetFileByServerRelativeUrl('" + soureRelativeUrl + "')/copyto(strnewurl='" + desRelativeUrl + "',boverwrite=false)"; 4 if (_documentType == Model.DocumentType.Personal) 5  { 6 RequestHelper.ClientID = _dicMapping[_userName]; 7  } 8 return RequestHelper.RequestPost(_userName, _appUrl, strCopyApi, _documentType); 9 }

總結

在寫接口的時候,在文件上傳的地方,卡了一天的時間,也就是昨天的時候,忽然查詢了Miscrosoft.SharePoint.Client下的File類,纔在網上看到那種實現方式,在羣裏也問了一些搞sharepoint的朋友,說那種方式操做起來更簡單一些,若是用Msdn中提到的那種方式使用Post提交數據,須要在請求頭中加一些參數。試了不少次無果,不得不放棄了。

下面是一些參考文章,但願對你有所幫助

https://msdn.microsoft.com/zh-SG/library/fp142385 OData相關

https://msdn.microsoft.com/zh-cn/library/jj164022.aspx

使用ClientObjectModel訪問SharePoint數據

http://blogs.msdn.com/b/uksharepoint/archive/2013/04/20/uploading-files-using-the-rest-api-and-client-side-techniques.aspx

http://my.oschina.net/edens/blog/115601

相關文章
相關標籤/搜索