博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[sharepoint]rest api文档库文件上传,下载,拷贝,剪切,删除文件,创建文件夹,修改文件夹属性,删除文件夹,获取文档列表...
阅读量:6437 次
发布时间:2019-06-23

本文共 15602 字,大约阅读时间需要 52 分钟。

写在前面

最近对文档库的知识点进行了整理,也就有了这篇文章,当时查找这些接口,并用在实践中,确实废了一些功夫,也为了让更多的人走更少的弯路。

系列文章

文件上传

通过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{    ///     /// 请求辅助类    ///     public class RequestHelper    {        private UserInfo _userInfo;        private string _url;        public RequestHelper(string url, UserInfo userInfo)        {            _url = url;            _userInfo = userInfo;        }        ///         /// 获取站点contextInfo信息        ///         /// 
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; } } /// /// 创建文件夹 /// /// 要创建文件夹的相对路径 ///
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; } /// /// 修改文件夹 /// /// ///
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; } /// /// 移除文件 /// /// ///
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; } /// /// 文件移动或者拷贝 /// /// ///
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; } /// /// 上传文件 /// /// /// ///
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; } /// /// 下载文件 /// /// 下载文件的api /// 在服务端保存的路径 ///
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; } } /// /// get请求 /// ///
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://vvzwo.baihongyu.com/

你可能感兴趣的文章
Facebook开发的一种数据查询语言——GraphQL:安全概述和测试技巧
查看>>
ECS主动运维2.0,体验升级,事半功倍
查看>>
vim 学习方法
查看>>
php token验证范例
查看>>
WebSocket的C++服务器端实现
查看>>
java中两种添加监听器的策略
查看>>
脑洞成现实!AI系统可提前10s预测地震
查看>>
oracle数据库的启动和停止
查看>>
《LoadRunner没有告诉你的》之七——使用 LoadRunner 连续长时间执行测试,如何保证参数化的数据足够又不会重复?...
查看>>
python easy_install django 安装
查看>>
读《图解HTTP》总结--第六章
查看>>
毕业就能拿到上万薪资的程序员他们都做了啥?
查看>>
最小的k个数
查看>>
iOS技巧之获取本机通讯录中的内容,解析通讯录源代码
查看>>
程序员从零到月薪15K的转变,python200G资料分享
查看>>
DNS域名解析的知识了解
查看>>
部署社交网站
查看>>
CentOS下如何修改主机名
查看>>
“机器人商店”是什么?卖机器人的吗?
查看>>
SVN的代码正确提交方法
查看>>