[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

时间: 2024-11-09 08:47:52

[sharepoint]rest api文档库文件上传,下载,拷贝,剪切,删除文件,创建文件夹,修改文件夹属性,删除文件夹,获取文档列表的相关文章

跟我学SharePoint 2013视频培训课程——怎样创建文档库并上传文档(8)

课程简介 第8天,怎样在SharePoint 2013怎样创建文档库并上传文档. 视频 SharePoint 2013 交流群 41032413

文件上传下载—servlet API实现

servlet API实现文件上传下载需要的jar包: UploadServlet.java package com.ymw.web.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; import javax.servl

文件上传下载

1.文件上传 文件上传下载本质是通过Socket的字节流来传输数据的.所以,对于文件上传,我们可以从HttpRequest对象获取输入流,进而获取上传文件的内容.但是采用ServletAPI并不能获取获取对应文件的字节流,而是获取整个Socket的字节流,里面包括提交的参数.上传文件内容以及其他附加信息. Servlet API上传文件,代码如下 protected void doPost(HttpServletRequest request, HttpServletResponse respo

开源项目OkHttpPlus——支持GET、POST、UI线程回调、JSON格式解析、链式调用、文件上传下载

OkHttpPlus介绍 项目地址:https://github.com/ZhaoKaiQiang/OkHttpPlus 主要功能:OkHttp封装,支持GET.POST.UI线程回调.JSON格式解析.链式调用.小文件上传下载及进度监听等功能 为什么要写这么一个库呢? 首先,是因为OkHttp在4.4之后已经作为底层的Http实现了,所以OkHttp这个库很强大,值得我们学习. 其次,在我看来,OkHttp使用起来不如Volley方便,OkHttp的回调都是在工作线程,所以如果在回调里面操作V

关于使用SecureCRT 实现 WIN7 与 Linux 双向通信的问题及文件上传下载

Linux 版本:Cent 6.5 X86 VMware workstation 10.0 win7 Ultimate x86 ,Linux 均可以正常链接网络[采用桥接方式] 遇到问题: win7 可以 ping 通linux及网关,linux不能ping通网关及win7,但能链接网络. 前提: 需要手动配置linux的IP为静态,WIN7的可以随意,但是一般在一个网段(不然配置较复杂了),保证可以正常通信访问. 解决: 通过手动改ip及相关配置的方法之后,仍然未能ping通,改链接方式为NA

文件上传下载之文件上传

13.1  文件上传 13.1.1  概述 在开发基于Web的应用的时候,经常会碰到需要实现文件上传.下载的功能,比如编辑某个商品,需要给它上传一个图片等等. 不使用Struts2的话,可以有很多种方式来实现文件上传,比如使用Apache的Common-FileUpload等.但是这些传统的方式,实现起来非常麻烦,需要写很多代码来进行控制. 现在使用Struts2来实现文件上传的功能,会更加简单和方便,事实上,Struts2的文件上传功能,默认就是基于Common-FileUpload来实现的,

java web 文件上传下载

文件上传下载案例: 首先是此案例工程的目录结构: 处理上传: FileUploadServlet.java 1 package fnz.fileUploadTest; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.PrintWriter; 7 import java.text.SimpleDateFormat; 8 import java.

.Net Core 图片文件上传下载

当下.Net Core项目可是如雨后春笋一般发展起来,作为.Net大军中的一员,我热忱地拥抱了.Net Core并且积极使用其进行业务的开发,我们先介绍下.Net Core项目下实现文件上传下载接口. 一.开发环境 毋庸置疑,宇宙第一IDE VisualStudio 2017 二.项目结构 FilesController 文件上传下载控制器 PictureController 图片上传下载控制器 Return_Helper_DG 返回值帮助类 三.关键代码 1.首先我们来看Startup.cs

Struts2学习之文件上传/下载&amp;ValueStack(三)

简介 今天是学习Struts2第三天,也算struts2准备前奏告一段落,提升部分只能在后期深入了解,多看源码,多参阅资料.今天所学的知识点文件上传.下载/ValueStack&OGNL/Struts2标签 文件上传/下载 文件上传简介 a). 企业常用文件上传技术 : jspSmartUpload(主要应用 JSP model1 时代) . fileupload (Apache commons项目中一个组件). Servlet3.0 集成文件上传 Part类 b). Struts2 对文件上传

javaEE(10)_文件上传下载

一.文件上传概述 1.实现web开发中的文件上传功能,需完成如下二步操作: •在web页面中添加上传输入项•在servlet中读取上传文件的数据,并保存到本地硬盘中. 2.如何在web页面中添加上传输入项?    <input type=“file”>标签用于在web页面中添加文件上传输入项,设置文件上传输入项时须注意:•必须要设置input输入项的name属性,否则浏览器将不会发送上传文件的数据.•必须把form的enctype属值设为multipart/form-data.设置该值后,浏览