博客地址:http://blog.csdn.net/FoxDave

本篇主要通过两个代码示例来展示如何应用REST API和jQuery上传文件到SharePoint。

示例会使用REST接口和jQuery AJAX请求来将一个本地文件添加到SharePoint文档库并修改它的一些属性。主要有以下几个操作步骤:

1. 使用FileReader API将本地文件转换成数组(需要HTML5支持),jQuery的(document).ready函数会检查浏览器对FileReader API的支持情况。

2. 使用文件夹的文件集合对象的Add方法将文件添加到文档库,将数组缓冲放到POST请求的body里。本文介绍的示例会使用getfolderbyserverrelativeurl端点来获取文件集合对象,如果不用这个,你也可以使用列表端点如…/_api/web/lists/getbytitle('<list title>')/rootfolder/files/add。

3. 使用ListItemAllFields属性来获取与上传文件相对应的列表项。

4. 使用MERGE请求来更改列表项的标题和显示名。

运行代码示例

本文中的两个代码示例使用REST API和jQuery AJAX请求来上传文件到文档库,然后更改对应列表项的属性。第一个例子使用SP.AppContextSite来跨SharePoint域进行调用,就像SharePoint承载的Add-in在上传文件到承载它的网站时做的那样。另一个例子是在同域调用的,就像上传到Add-in所在的网站时做的那样。

注意用JavaScript编写的提供程序承载的Add-in必须使用SP.RequestExecutor跨域库来向SharePoint域发送请求。

使用本文提到的示例,你需要做以下事情:

1. 首先你要有SharePoint Server 2013、2016或者是Online的环境。

2. 执行代码的用户需要有对文档库的写权限,如果你开发的是一个SharePoint Add-in的话,你可以在列表范围指定写权限。

3. 支持FileReader API(HTML5)的浏览器。

4. 在你的页面中引用jQuery库,例如:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>

5. 在你的页面中添加以下控件:

<input id="getFile" type="file"/><br />
<input id="displayName" type="text" value="Enter a unique name" /><br />
<input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>

代码示例一:使用REST API和jQuery跨SharePoint域上传文件

大师傅下面的代码示例将文件上传到承载SharePoint Add-in的SharePoint网站。

'use strict';

var appWebUrl, hostWebUrl;

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
if (!window.FileReader) {
alert('This browser does not support the FileReader API.');
} // Get the add-in web and host web URLs.
appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
}); // Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() { // Define the folder path for this example.
var serverRelativeUrlToFolder = '/shared documents'; // Get test values from the file input and text input page controls.
// The display name must be unique every time you run the example.
var fileInput = jQuery('#getFile');
var newName = jQuery('#displayName').val(); // Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer();
getFile.done(function (arrayBuffer) { // Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer);
addFile.done(function (file, status, xhr) { // Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) { // Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
alert('file uploaded and updated');
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError); // Get the local file as an array buffer.
function getFileBuffer() {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(fileInput[0].files[0]);
return deferred.promise();
} // Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page.
var parts = fileInput[0].value.split('\\');
var fileName = parts[parts.length - 1]; // Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
"/add(overwrite=true, url='{2}')?@target='{3}'",
appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl); // Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
}
});
} // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
function getListItem(fileListItemUri) { // Construct the endpoint.
// The list item URI uses the host web, but the cross-domain call is sent to the
// add-in web and specifies the host web as the context site.
fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web'); var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
appWebUrl, hostWebUrl); // Send the request and return the response.
return jQuery.ajax({
url: listItemAllFieldsEndpoint,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
});
} // Change the display name and title of the list item.
function updateListItem(itemMetadata) { // Construct the endpoint.
// Specify the host web as the context site.
var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl); // Define the list item changes. Use the FileLeafRef property to change the display name.
// For simplicity, also use the name as the title.
// The example gets the list item type from the item's metadata, but you can also get it from the
// ListItemEntityTypeFullName property of the list.
var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
itemMetadata.type, newName, newName); // Send the request and return the promise.
// This call does not return response content from the server.
return jQuery.ajax({
url: listItemEndpoint,
type: "POST",
data: body,
headers: {
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose",
"content-length": body.length,
"IF-MATCH": itemMetadata.etag,
"X-HTTP-Method": "MERGE"
}
});
}
} // Display error messages.
function onError(error) {
alert(error.responseText);
} // Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) return singleParam[1];
}
}

代码示例二:使用REST API和jQuery将文件上传到同域网站

'use strict';

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
if (!window.FileReader) {
alert('This browser does not support the FileReader API.');
}
}); // Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() { // Define the folder path for this example.
var serverRelativeUrlToFolder = '/shared documents'; // Get test values from the file input and text input page controls.
var fileInput = jQuery('#getFile');
var newName = jQuery('#displayName').val(); // Get the server URL.
var serverUrl = _spPageContextInfo.webAbsoluteUrl; // Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer();
getFile.done(function (arrayBuffer) { // Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer);
addFile.done(function (file, status, xhr) { // Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) { // Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
alert('file uploaded and updated');
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError); // Get the local file as an array buffer.
function getFileBuffer() {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(fileInput[0].files[0]);
return deferred.promise();
} // Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page.
var parts = fileInput[0].value.split('\\');
var fileName = parts[parts.length - 1]; // Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
"/add(overwrite=true, url='{2}')",
serverUrl, serverRelativeUrlToFolder, fileName); // Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
}
});
} // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
function getListItem(fileListItemUri) { // Send the request and return the response.
return jQuery.ajax({
url: fileListItemUri,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
});
} // Change the display name and title of the list item.
function updateListItem(itemMetadata) { // Define the list item changes. Use the FileLeafRef property to change the display name.
// For simplicity, also use the name as the title.
// The example gets the list item type from the item's metadata, but you can also get it from the
// ListItemEntityTypeFullName property of the list.
var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
itemMetadata.type, newName, newName); // Send the request and return the promise.
// This call does not return response content from the server.
return jQuery.ajax({
url: itemMetadata.uri,
type: "POST",
data: body,
headers: {
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose",
"content-length": body.length,
"IF-MATCH": itemMetadata.etag,
"X-HTTP-Method": "MERGE"
}
});
}
} // Display error messages.
function onError(error) {
alert(error.responseText);
}

本篇就到这里。

SharePoint REST API - 使用REST API和jQuery上传一个文件的更多相关文章

  1. jQuery上传插件,文件上传测试用例

    jQuery上传插件,文件上传测试用例 jQuery File Upload-jQuery上传插件介绍http://www.jq22.com/jquery-info230 jQuery File Up ...

  2. Web API之基于H5客户端分段上传大文件

    http://www.cnblogs.com/OneDirection/articles/7285739.html 查询很多资料没有遇到合适的,对于MultipartFormDataStreamPro ...

  3. File API 读取上传的文件

    1, 在html 文档中,<input type="file"> 我们可以选择文件进行上传,但这时只能上传一个文件.如果加上multiple 属性,可以上传多个文件,上 ...

  4. JQuery上传插件Uploadify详解及其中文按钮解决方案 .

    Uploadify有一个参数是 buttonText 这个无论你怎么改都不支持中文,因为插件在js里用了一个转码方法把这个参数的值转过码了,解码的地方在那个swf文件里,看不到代码,所以这条路不行. ...

  5. 利用Java API通过路径过滤上传多文件至HDFS

    在本地文件上传至HDFS过程中,很多情况下一个目录包含很多个文件,而我们需要对这些文件进行筛选,选出符合我们要求的文件,上传至HDFS.这时就需要我们用到文件模式. 在项目开始前,我们先掌握文件模式 ...

  6. jquery上传文件控件Uploadify

    基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件. 要求使用jquery1.4或以上版本,flash player 9.0.24以上. 有两个 ...

  7. jquery 上传空间uploadify使用笔记

    基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件. 要求使用jquery1.4或以上版本,flash player 9.0.24以上. 有两个 ...

  8. jQuery上传插件Uploadify 3.2使用

    Uploadify下载地址:http://www.uploadify.com/download/ 这里下载最新版的3.2的. 常用API描述: $(document).ready(function() ...

  9. 利用SkyDrive Pro 迅速批量下载SharePoint Server 上已上传的文件

    在上一篇<SharePoint Server 2013 让上传文件更精彩>,我们一起了解了如何快速的方便的上传批量文件到SharePoint Server 2013 ,而在这一篇日志中您将 ...

随机推荐

  1. elasticsearch 安装 windows linux macOS

    导读 在上一章节我们介绍Elasticsearch基本概念,今天我们继续进行本章内容,Elasticsearch在各种环境下安装,下面将逐一讲解在各种操作系统或不同安装在不同环境中注意事项. 安装 E ...

  2. BeautifulReport--适用于unittest自动化测试的可视化报告

    安装: 因为是由大神分享的,可以直接在github<https://github.com/TesterlifeRaymond/BeautifulReport>上下载 git clone g ...

  3. Rest和Restful & http

    Rest :Representational State Transfer 表述性状态转移 Restful: Rest+ful形容词,遵循Rest原则的应用程序或设计 Rest原则: 1. 网络上的所 ...

  4. 关于oracle result_cache

    结果集缓存 和聚合物化视图类似,报表系统和数据仓库系统是最适合结果集缓存的,这些系统通常具有大量复杂的SQL,其中不少子查询包含聚合函数,如果能够尽可能重用这些已经计算过的聚合结果集,将极大的提升系统 ...

  5. 剑指offer(27)字符串的排列

    题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述:输入 ...

  6. 剑指offer(54)字符流中第一个不重复的数字

    题目描述 请实现一个函数用来找出字符流中第一个只出现一次的字符.例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g".当从该字符流中读出 ...

  7. maven+springmvc出现:java.sql.SQLException: Unknown system variable 'query_cache_size'

    连接mysql时一直出现以下的错误: org.springframework.web.util.NestedServletException: Request processing failed; n ...

  8. Caused by: java.lang.NoClassDefFoundError: com/google/common/base/MoreObjects

    环境:jdk1.8 开发工具:IDEA 说明:今天在做springboot集成swagger2的时候,在启动程序的时候,报错 报错信息: Error starting ApplicationConte ...

  9. 【分布式搜索引擎】Elasticsearch写入和读取数据过程

    一.Elasticsearch写人数据的过程 1)客户端选择一个node发送请求过去,这个node就是coordinating node(协调节点)2)coordinating node,对docum ...

  10. vue 上拉加载自定义组件,超好用哦

    1.创建组件components > zj-roll > index.vue <template> <div> <slot></slot> ...