本篇主要通过两个代码示例来展示如何应用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