SharePoint REST API - 使用REST API和jQuery上传一个文件

叁歲伎倆 2022-04-03 08:10 301阅读 0赞

本篇主要通过两个代码示例来展示如何应用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(‘‘)/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库,例如:

  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
  1. 在你的页面中添加以下控件:
  1. <input id="getFile" type="file"/><br />
  2. <input id="displayName" type="text" value="Enter a unique name" /><br />
  3. <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>

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

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

  1. 'use strict';
  2. var appWebUrl, hostWebUrl;
  3. jQuery(document).ready(function () {
  4. // Check for FileReader API (HTML5) support.
  5. if (!window.FileReader) {
  6. alert('This browser does not support the FileReader API.');
  7. }
  8. // Get the add-in web and host web URLs.
  9. appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
  10. hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  11. });
  12. // Upload the file.
  13. // You can upload files up to 2 GB with the REST API.
  14. function uploadFile() {
  15. // Define the folder path for this example.
  16. var serverRelativeUrlToFolder = '/shared documents';
  17. // Get test values from the file input and text input page controls.
  18. // The display name must be unique every time you run the example.
  19. var fileInput = jQuery('#getFile');
  20. var newName = jQuery('#displayName').val();
  21. // Initiate method calls using jQuery promises.
  22. // Get the local file as an array buffer.
  23. var getFile = getFileBuffer();
  24. getFile.done(function (arrayBuffer) {
  25. // Add the file to the SharePoint folder.
  26. var addFile = addFileToFolder(arrayBuffer);
  27. addFile.done(function (file, status, xhr) {
  28. // Get the list item that corresponds to the uploaded file.
  29. var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
  30. getItem.done(function (listItem, status, xhr) {
  31. // Change the display name and title of the list item.
  32. var changeItem = updateListItem(listItem.d.__metadata);
  33. changeItem.done(function (data, status, xhr) {
  34. alert('file uploaded and updated');
  35. });
  36. changeItem.fail(onError);
  37. });
  38. getItem.fail(onError);
  39. });
  40. addFile.fail(onError);
  41. });
  42. getFile.fail(onError);
  43. // Get the local file as an array buffer.
  44. function getFileBuffer() {
  45. var deferred = jQuery.Deferred();
  46. var reader = new FileReader();
  47. reader.onloadend = function (e) {
  48. deferred.resolve(e.target.result);
  49. }
  50. reader.onerror = function (e) {
  51. deferred.reject(e.target.error);
  52. }
  53. reader.readAsArrayBuffer(fileInput[0].files[0]);
  54. return deferred.promise();
  55. }
  56. // Add the file to the file collection in the Shared Documents folder.
  57. function addFileToFolder(arrayBuffer) {
  58. // Get the file name from the file input control on the page.
  59. var parts = fileInput[0].value.split('\\');
  60. var fileName = parts[parts.length - 1];
  61. // Construct the endpoint.
  62. var fileCollectionEndpoint = String.format(
  63. "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
  64. "/add(overwrite=true, url='{2}')?@target='{3}'",
  65. appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
  66. // Send the request and return the response.
  67. // This call returns the SharePoint file.
  68. return jQuery.ajax({
  69. url: fileCollectionEndpoint,
  70. type: "POST",
  71. data: arrayBuffer,
  72. processData: false,
  73. headers: {
  74. "accept": "application/json;odata=verbose",
  75. "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
  76. "content-length": arrayBuffer.byteLength
  77. }
  78. });
  79. }
  80. // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
  81. function getListItem(fileListItemUri) {
  82. // Construct the endpoint.
  83. // The list item URI uses the host web, but the cross-domain call is sent to the
  84. // add-in web and specifies the host web as the context site.
  85. fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
  86. fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
  87. var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
  88. appWebUrl, hostWebUrl);
  89. // Send the request and return the response.
  90. return jQuery.ajax({
  91. url: listItemAllFieldsEndpoint,
  92. type: "GET",
  93. headers: { "accept": "application/json;odata=verbose" }
  94. });
  95. }
  96. // Change the display name and title of the list item.
  97. function updateListItem(itemMetadata) {
  98. // Construct the endpoint.
  99. // Specify the host web as the context site.
  100. var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
  101. var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);
  102. // Define the list item changes. Use the FileLeafRef property to change the display name.
  103. // For simplicity, also use the name as the title.
  104. // The example gets the list item type from the item's metadata, but you can also get it from the
  105. // ListItemEntityTypeFullName property of the list.
  106. var body = String.format("{
  107. {'__metadata':{
  108. {'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
  109. itemMetadata.type, newName, newName);
  110. // Send the request and return the promise.
  111. // This call does not return response content from the server.
  112. return jQuery.ajax({
  113. url: listItemEndpoint,
  114. type: "POST",
  115. data: body,
  116. headers: {
  117. "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
  118. "content-type": "application/json;odata=verbose",
  119. "content-length": body.length,
  120. "IF-MATCH": itemMetadata.etag,
  121. "X-HTTP-Method": "MERGE"
  122. }
  123. });
  124. }
  125. }
  126. // Display error messages.
  127. function onError(error) {
  128. alert(error.responseText);
  129. }
  130. // Get parameters from the query string.
  131. // For production purposes you may want to use a library to handle the query string.
  132. function getQueryStringParameter(paramToRetrieve) {
  133. var params = document.URL.split("?")[1].split("&");
  134. for (var i = 0; i < params.length; i = i + 1) {
  135. var singleParam = params[i].split("=");
  136. if (singleParam[0] == paramToRetrieve) return singleParam[1];
  137. }
  138. }

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

  1. 'use strict';
  2. jQuery(document).ready(function () {
  3. // Check for FileReader API (HTML5) support.
  4. if (!window.FileReader) {
  5. alert('This browser does not support the FileReader API.');
  6. }
  7. });
  8. // Upload the file.
  9. // You can upload files up to 2 GB with the REST API.
  10. function uploadFile() {
  11. // Define the folder path for this example.
  12. var serverRelativeUrlToFolder = '/shared documents';
  13. // Get test values from the file input and text input page controls.
  14. var fileInput = jQuery('#getFile');
  15. var newName = jQuery('#displayName').val();
  16. // Get the server URL.
  17. var serverUrl = _spPageContextInfo.webAbsoluteUrl;
  18. // Initiate method calls using jQuery promises.
  19. // Get the local file as an array buffer.
  20. var getFile = getFileBuffer();
  21. getFile.done(function (arrayBuffer) {
  22. // Add the file to the SharePoint folder.
  23. var addFile = addFileToFolder(arrayBuffer);
  24. addFile.done(function (file, status, xhr) {
  25. // Get the list item that corresponds to the uploaded file.
  26. var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
  27. getItem.done(function (listItem, status, xhr) {
  28. // Change the display name and title of the list item.
  29. var changeItem = updateListItem(listItem.d.__metadata);
  30. changeItem.done(function (data, status, xhr) {
  31. alert('file uploaded and updated');
  32. });
  33. changeItem.fail(onError);
  34. });
  35. getItem.fail(onError);
  36. });
  37. addFile.fail(onError);
  38. });
  39. getFile.fail(onError);
  40. // Get the local file as an array buffer.
  41. function getFileBuffer() {
  42. var deferred = jQuery.Deferred();
  43. var reader = new FileReader();
  44. reader.onloadend = function (e) {
  45. deferred.resolve(e.target.result);
  46. }
  47. reader.onerror = function (e) {
  48. deferred.reject(e.target.error);
  49. }
  50. reader.readAsArrayBuffer(fileInput[0].files[0]);
  51. return deferred.promise();
  52. }
  53. // Add the file to the file collection in the Shared Documents folder.
  54. function addFileToFolder(arrayBuffer) {
  55. // Get the file name from the file input control on the page.
  56. var parts = fileInput[0].value.split('\\');
  57. var fileName = parts[parts.length - 1];
  58. // Construct the endpoint.
  59. var fileCollectionEndpoint = String.format(
  60. "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
  61. "/add(overwrite=true, url='{2}')",
  62. serverUrl, serverRelativeUrlToFolder, fileName);
  63. // Send the request and return the response.
  64. // This call returns the SharePoint file.
  65. return jQuery.ajax({
  66. url: fileCollectionEndpoint,
  67. type: "POST",
  68. data: arrayBuffer,
  69. processData: false,
  70. headers: {
  71. "accept": "application/json;odata=verbose",
  72. "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
  73. "content-length": arrayBuffer.byteLength
  74. }
  75. });
  76. }
  77. // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
  78. function getListItem(fileListItemUri) {
  79. // Send the request and return the response.
  80. return jQuery.ajax({
  81. url: fileListItemUri,
  82. type: "GET",
  83. headers: { "accept": "application/json;odata=verbose" }
  84. });
  85. }
  86. // Change the display name and title of the list item.
  87. function updateListItem(itemMetadata) {
  88. // Define the list item changes. Use the FileLeafRef property to change the display name.
  89. // For simplicity, also use the name as the title.
  90. // The example gets the list item type from the item's metadata, but you can also get it from the
  91. // ListItemEntityTypeFullName property of the list.
  92. var body = String.format("{
  93. {'__metadata':{
  94. {'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
  95. itemMetadata.type, newName, newName);
  96. // Send the request and return the promise.
  97. // This call does not return response content from the server.
  98. return jQuery.ajax({
  99. url: itemMetadata.uri,
  100. type: "POST",
  101. data: body,
  102. headers: {
  103. "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
  104. "content-type": "application/json;odata=verbose",
  105. "content-length": body.length,
  106. "IF-MATCH": itemMetadata.etag,
  107. "X-HTTP-Method": "MERGE"
  108. }
  109. });
  110. }
  111. }
  112. // Display error messages.
  113. function onError(error) {
  114. alert(error.responseText);
  115. }

本篇就到这里。

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读

    相关 restful api

    简介 一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实