写在前面
最近对文档库的知识点进行了整理,也就有了这篇文章,当时查找这些接口,并用在实践中,确实废了一些功夫,也为了让更多的人走更少的弯路。
系列文章
WebHttpRequest在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.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
博客地址: | http://www.cnblogs.com/wolf-sun/ |
博客版权: | 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。 如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。http://www.cnblogs.com/wolf-sun/p/4760228.html |