[sharepoint]rest api文檔庫文件上傳,下載,拷貝,剪切,刪除文件,創建文件夾,修改文件夾屬性,刪除文件夾,獲取文檔列表


寫在前面

最近對文檔庫的知識點進行了整理,也就有了這篇文章,當時查找這些接口,並用在實踐中,確實廢了一些功夫,也為了讓更多的人走更少的彎路。

系列文章

sharepoint環境安裝過程中幾點需要注意的地方

Rest API的簡單應用

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

通過WebClient模擬post上傳文件到服務器

WebHttpRequest在sharepoint文檔庫中的使用

[sharepoint]Rest api相關知識(轉)

[sharepoint]根據用戶名獲取該用戶的權限

[sharepoint]根據用戶名獲取該用戶的權限

[sharepoint]修改Item或者File的Author和Editor

文件上傳

通過rest api上傳到sharepoint文檔庫。

上傳文件api

string strApi = "GetFolderByServerRelativeUrl('" + strFileServerRelativeUrl + "')/Files/Add(url='" + strFileName + "',overwrite=true)?$select=Name,ServerRelativeUrl,TimeCreated,TimeLastModified,Exists,Length";

strFileServerRelativeUrl:文件在sharepoint文檔庫中的相對路徑,比如:/server/libdoc11/test/.
strFileName:文件名稱。
overwrite:如果文件在文檔庫中已經存在,是否進行覆蓋。
$select:odata查詢關鍵字,進行篩選字段,這里是在文件上傳成功后,返回該文件的相關信息。

文件下載

文件下載api

 string loadApi = "GetFileByServerRelativeUrl('" + serverRelativeUrl + "')/$value";

serverRelativeUrl:文件的相對路徑,比如:/server/libdoc11/test/1.txt

文件拷貝

 string strCopyApi = "GetFileByServerRelativeUrl('" + strSourceUrl + "')/copyto(strnewurl='" + strTargetUrl + "',boverwrite=true)";

strSourceUrl:拷貝文件的相對路徑,比如:/server/libdoc11/test/1.txt

strTargetUrl:目標路徑,比如:比如:/server/libdoc11/test2/1.txt

boverwrite:是否覆蓋

文件剪切

string strMoveToApi = "GetFileByServerRelativeUrl('" + strSourceUrl + "')/moveto(newurl='" + strTargetUrl + "',flags=1)";

strSourceUrl:拷貝文件的相對路徑,比如:/server/libdoc11/test/1.txt

strTargetUrl:目標路徑,比如:比如:/server/libdoc11/test2/1.txt

flags:1是否覆蓋

刪除文件

 刪除文件的接口,與獲取文件的接口一樣,只不過區別在發送的請求不通,一個是get請求,一個是delete請求。

string queryFileApi = "GetFileByServerRelativeUrl('" + serverRelativeUrl + "')";
 string strFileApi = "GetFolderByServerRelativeUrl('" + strFileServerRelativeUrl + "')/Files?$filter=Name eq '" + strFileName + "'&$select=Name,ServerRelativeUrl,TimeCreated,TimeLastModified,Exists,Length";

 上面兩個都是可以得,第二種是使用odata查詢$filter關鍵字進行篩選,文件名稱等於要刪除的文件名就可以了,並返回刪除的文件信息。

獲取文檔列表

               string strFileApi = "GetFolderByServerRelativeUrl('" + strServerRelative + "')/Files?$orderby=TimeCreated desc&$select=Author/Title,ModifiedBy/Title,CheckInComment,Name,ServerRelativeUrl,TimeCreated,TimeLastModified,Exists,Length&$expand=Author/Title,ModifiedBy/Title";
                string strFolderApi = "GetFolderByServerRelativeUrl('" + strServerRelative + "')/Folders?$filter=Name ne 'Forms'&$select=Name,ServerRelativeUrl,ItemCount";
             

上面的是獲取某個文檔庫的文件列表。並返回需要的屬性。下面的接口為獲取所有的文件夾,當然可以根據傳入的相對路徑,獲取子目錄中的所有文件夾,其中Forms為默認隱藏的目錄,可以將其過濾掉,這里是篩選所有不文件夾名字不等於Forms的目錄。

注意

在返回文件的創建者與編輯者時,需要使用Author/Title,ModifiedBy/Tilte,因為Author與ModifiedBy在sharepoint端是User對象,並且這時候你會發現這樣仍不能正確的顯示創建者與編輯者,這時候就需要用到odata查詢的$expand關鍵字。

創建文件夾

string strCreateFolderApi = "folders/add('" + serverRelativeUrl + "/" + folderName + "')";

 serverRelativeUrl:相對路徑,就是要在哪兒創建文件夾。

一個請求輔助類

 各個請求請對號入座

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.AngularJs
{
    /// <summary>
    /// 請求輔助類
    /// </summary>
    public class RequestHelper
    {
        private UserInfo _userInfo;
        private string _url;
        public RequestHelper(string url, UserInfo userInfo)
        {
            _url = url;
            _userInfo = userInfo;
        }
        /// <summary>
        /// 獲取站點contextInfo信息
        /// </summary>
        /// <returns></returns>
        public string GetContextinfo()
        {
            HttpWebRequest contextInfoRequest = null;
            HttpWebResponse endpointResponse = null;
            StreamReader sr = null;
            string strJson = string.Empty;
            try
            {
                //獲取contextinfo
                contextInfoRequest = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/contextinfo");
                contextInfoRequest.Method = "POST";
                contextInfoRequest.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                contextInfoRequest.Accept = "application/json;odata=verbose";
                contextInfoRequest.ContentLength = 0;
                using (endpointResponse = (HttpWebResponse)contextInfoRequest.GetResponse())
                {
                    using (sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                        JObject jobj = JObject.Parse(strJson);
                        return jobj["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 創建文件夾
        /// </summary>
        /// <param name="strName">要創建文件夾的相對路徑</param>
        /// <returns></returns>
        public string CreateFolder(string serverRelativeUrl)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebResponse response = null;
            StreamReader sr = null;
            HttpWebRequest request = null;
            try
            {
                string metadata = "{'__metadata': { 'type': 'SP.Folder' },'ServerRelativeUrl':'" + serverRelativeUrl + "'}";
                byte[] buffer = Encoding.UTF8.GetBytes(metadata);
                request = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/folders");
                request.Method = "POST";
                request.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                request.Accept = "application/json;odata=verbose";
                request.ContentLength = buffer.Length;
                request.ContentType = "application/json;odata=verbose";
                request.Headers.Add("X-RequestDigest", this.GetContextinfo());
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(buffer, 0, buffer.Length);
                }
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return strJson;
        }
        /// <summary>
        /// 修改文件夾
        /// </summary>
        /// <param name="strAPI"></param>
        /// <returns></returns>
        public string UpdateFolder(string folderRelativeUrl, string strName)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebResponse response = null;
            StreamReader sr = null;
            HttpWebRequest request = null;
            try
            {
                string metadata = "{'__metadata': {'type': 'SP.Folder'},'Name':'" + strName + "','ServerRelativeUrl':'" + folderRelativeUrl + "'}";
                byte[] buffer = Encoding.UTF8.GetBytes(metadata);
                request = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/GetFolderByServerRelativeUrl('" + folderRelativeUrl + "')");
                request.Method = "POST";
                request.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                request.Accept = "application/json;odata=verbose";
                request.ContentLength = buffer.Length;
                request.ContentType = "application/json;odata=verbose";
                request.Headers.Add("IF-MATCH", "*");
                request.Headers.Add("X-HTTP-Method", "MERGE");
                request.Headers.Add("X-RequestDigest", this.GetContextinfo());
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(buffer, 0, buffer.Length);
                }
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return strJson;
        }
        /// <summary>
        /// 移除文件
        /// </summary>
        /// <param name="fileRelativeUrl"></param>
        /// <returns></returns>
        public string RemoveFile(string fileRelativeUrl)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebResponse response = null;
            StreamReader sr = null;
            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/GetFileByServerRelativeUrl('" + fileRelativeUrl + "')");
                request.Method = "POST";
                request.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                request.Accept = "application/json;odata=verbose";
                request.ContentLength = 0;
                request.ContentType = "application/json;odata=verbose";
                request.Headers.Add("IF-MATCH", "*");
                request.Headers.Add("X-HTTP-Method", "DELETE");
                request.Headers.Add("X-RequestDigest", this.GetContextinfo());
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return strJson;
        }
        /// <summary>
        /// 文件移動或者拷貝
        /// </summary>
        /// <param name="strAPi"></param>
        /// <returns></returns>
        public string CopyOrMoveTo(string strAPi)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebResponse response = null;
            StreamReader sr = null;
            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/" + strAPi);
                request.Method = "POST";
                request.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                request.Accept = "application/json;odata=verbose";
                request.ContentLength = 0;
                request.ContentType = "application/json;odata=verbose";
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return strJson;
        }
        /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="strApi"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string PostFile(string strApi, byte[] data)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebResponse fielResponse = null;
            StreamReader sr = null;
            HttpWebRequest fileRequest = null;
            try
            {
                fileRequest = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/" + strApi);
                fileRequest.Method = "POST";
                fileRequest.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                fileRequest.Accept = "application/json;odata=verbose";
                fileRequest.ContentLength = data.Length;
                fileRequest.Headers.Add("X-RequestDigest", this.GetContextinfo());
                using (Stream requestStream = fileRequest.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }
                using (fielResponse = (HttpWebResponse)fileRequest.GetResponse())
                {
                    using (sr = new StreamReader(fielResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return strJson;
        }
        /// <summary>
        /// 下載文件
        /// </summary>
        /// <param name="apiUrl">下載文件的api</param>
        /// <param name="filePath">在服務端保存的路徑</param>
        /// <returns></returns>
        public void DownLoadFile(string apiUrl, string filePath)
        {
            byte[] buffer = null;
            Uri hostWebUri = new Uri(_url);
            try
            {
                //下載的時候避免重名文件進行覆蓋
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_url + "/_api/web/" + apiUrl);
                request.Method = "GET";
                request.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                request.Accept = "application/json;odata=verbose";
                request.ContentType = "application/octet-stream";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            int bufferSize = 1024;
                            //緩沖
                            buffer = new byte[bufferSize];
                            //真實讀取的大小
                            int length = stream.Read(buffer, 0, bufferSize);
                            while (length > 0)
                            {
                                fs.Write(buffer, 0, length);
                                length = stream.Read(buffer, 0, bufferSize);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// get請求
        /// </summary>
        /// <returns></returns>
        public string RequestGet(string strApi)
        {
            string strJson = string.Empty;
            Uri hostWebUri = new Uri(_url);
            HttpWebRequest endpointRequest = null;
            HttpWebResponse endpointResponse = null;
            StreamReader sr = null;
            try
            {
                strApi = _url + "/_api/web/" + strApi;
                endpointRequest = (HttpWebRequest)HttpWebRequest.Create(strApi);
                endpointRequest.Credentials = new NetworkCredential(_userInfo.Itcode, _userInfo.Pwd, _userInfo.Doamin);
                endpointRequest.Method = "GET";
                endpointRequest.Accept = "application/json;odata=verbose";
                using (endpointResponse = (HttpWebResponse)endpointRequest.GetResponse())
                {
                    using (sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return strJson;
        }
    }
}

其中url為文檔庫的站點地址,比如文檔庫DocLib10的地址為Http://www.bb.com/site/DocLib10/AllItems.aspx.則Url為Http://www.bb.com/site/DocLib10。

買一送一接口

最后再奉上一個查詢某個文檔庫信息的接口

                string strDocApi = "lists?$filter=((EntityTypeName eq '" + strEntityName + "' or substringof('" + strEntityName + "',DocumentTemplateUrl)) and BaseTemplate eq 101)&$select=Id,EntityTypeName,ParentWebUrl,Title,BaseTemplate";

       使用odata查詢,文檔庫的BaseTemplate為101,這樣也可以獲取所有的文檔庫列表。

       substringof函數為:屬性值中包含某個字符串。以該接口為例,DocumentTemplateUrl中包含strEntityName的文檔庫。

總結

 這里將查詢到的,以及用到的接口總結在這里。在使用的時候,各種參數導致的請求失敗,當時頭都大了。而msdn上面大多都是js的,而且沒有詳細的demo,只能一個個的嘗試。通過文檔庫的rest api對sharepoint中的List,Item也有一個了解,知道一些操作該去怎么實現。使用場景:移動端集成sharepoint。

參考

 http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/using-$select,-$expand,-and-$value

 http://www.cnblogs.com/PurpleTide/archive/2010/12/21/1912395.html

 https://msdn.microsoft.com/zh-cn/magazine/dn198245.aspx

https://msdn.microsoft.com/en-us/library/jj860569.aspx


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM