SharePoint REST API - 使用REST API和jQuery上傳一個檔案
部落格地址: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);
}
本篇就到這裡。 相關文章
- rest apiRESTAPI
- GraphQL API vs REST APIAPIREST
- Spark REST API & metricsSparkRESTAPI
- Elasticsearch(二)——Rest APIElasticsearchRESTAPI
- [譯] 使用 Node 和 OAuth 2.0 構建一個簡單的 REST APIOAuthRESTAPI
- Elasticsearch 入門實戰(8)--REST API 使用二(Search API)ElasticsearchRESTAPI
- 使用JBang構建Spring Boot Rest API教程Spring BootRESTAPI
- 13 個設計 REST API 的最佳實踐RESTAPI
- kubernetes之使用http rest api訪問叢集HTTPRESTAPI
- 如何使用dotnet core 編寫REST風格APIRESTAPI
- rest-api設計風格RESTAPI
- Django REST framework API 指南(21):SchemasDjangoRESTFrameworkAPI
- Harbor配置Swagger遠端REST APISwaggerRESTAPI
- Django REST framework API 指南(27):SettingsDjangoRESTFrameworkAPI
- Django REST framework API 指南(15):限流DjangoRESTFrameworkAPI
- Django REST framework API 指南(7):解析DjangoRESTFrameworkAPI
- Django REST framework API 指南(8):渲染DjangoRESTFrameworkAPI
- Django REST framework API 指南(6):路由DjangoRESTFrameworkAPI路由
- Elepy,快速建立一個定製的網站和Rest API生成器網站RESTAPI
- 30秒無需編碼完成一個REST API服務RESTAPI
- Segment使用Go、gRPC和Envoy作為後端REST API實現GoRPC後端RESTAPI
- 筆記三:基本概念-文件、索引和 REST API筆記索引RESTAPI
- Pulsar 入門實戰(6)--Rest APIRESTAPI
- elasticsearch常用請求介面Rest API示例ElasticsearchRESTAPI
- 在 .NET Core 中構建 REST APIRESTAPI
- Django REST framework API 指南(17):分頁DjangoRESTFrameworkAPI
- Django REST framework API 指南(18):版本控制DjangoRESTFrameworkAPI
- Elasticsearch Java High Level REST Client(Exists API)ElasticsearchJavaRESTclientAPI
- Elasticsearch Java High Level REST Client(Delete API)ElasticsearchJavaRESTclientdeleteAPI
- REST API簽名認證機制RESTAPI
- Flask框架搭建REST-API服務Flask框架RESTAPI
- Django REST framework API 指南(13):認證DjangoRESTFrameworkAPI
- Django REST framework API 指南(23):返回 URLDjangoRESTFrameworkAPI
- Django REST framework API 指南(24):異常DjangoRESTFrameworkAPI
- Django REST framework API 指南(26):測試DjangoRESTFrameworkAPI
- Django REST framework API 指南(16):過濾DjangoRESTFrameworkAPI
- (16) SpringCloud-Eureka的REST API及API擴充套件SpringGCCloudRESTAPI套件
- 如何使用Spring Boot,Spring Data和H2 DB實現REST APISpring BootRESTAPI
- 用ASP.NET Core 2.1 建立規範的 REST API -- 保護API和其它ASP.NETRESTAPI