Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.24 KB | None | 0 0
  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
  2. <script src="https://site.sharepoint.com/_layouts/15/SP.RequestExecutor.js" type="text/javascript"></script>
  3.  
  4. <input id="getFile" type="file"/><br />
  5. <input id="displayName" type="text" value="Enter a unique name" /><br />
  6. <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>
  7. <input type="hidden" value="" id="__REQUESTDIGEST">
  8. 'use strict';
  9.  
  10. var appWebUrl, hostWebUrl;
  11. String.format = function () {
  12. var s = arguments[0];
  13. for (var i = 0; i < arguments.length - 1; i += 1) {
  14. var reg = new RegExp('\{' + i + '\}', 'gm');
  15. s = s.replace(reg, arguments[i + 1]);
  16. }
  17. return s;
  18. };
  19.  
  20.  
  21.  
  22. jQuery(document).ready(function () {
  23. var getFormDgst= function() {
  24.  
  25. var req = {};
  26. req.url = "https://site.sharepoint.com/sites/sitename/_api/contextinfo";
  27. req.method = "POST";
  28. req.body = "";
  29. req.headers = {
  30. "Authorization" : "Bearer <?= $site->getSPAccessToken()?>",
  31. "Accept" : "application/json; odata=verbose",
  32. };
  33. req.success = function(data) {
  34. //get context info from data.
  35. jQuery('#__REQUESTDIGEST').val(data.d.GetContextWebInformation.FormDigestValue)
  36.  
  37. };
  38. req.failure = function(data, errorCode, errorMessage) {
  39.  
  40. }
  41. jQuery.ajax(req);
  42. }
  43.  
  44. getFormDgst();
  45. // Check for FileReader API (HTML5) support.
  46. if (!window.FileReader) {
  47. alert('This browser does not support the FileReader API.');
  48. }
  49.  
  50. // Get the add-in web and host web URLs.
  51.  
  52. appWebUrl = "https://site.sharepoint.com/sites/sitename";
  53. hostWebUrl = "<?= $siteUrl ?>";
  54. });
  55.  
  56. // Upload the file.
  57. // You can upload files up to 2 GB with the REST API.
  58. function uploadFile() {
  59.  
  60. // Define the folder path for this example.
  61. var serverRelativeUrlToFolder = 'AppCatalog/video/';
  62.  
  63. // Get test values from the file input and text input page controls.
  64. // The display name must be unique every time you run the example.
  65. var fileInput = jQuery('#getFile');
  66. var newName = jQuery('#displayName').val();
  67.  
  68. // Initiate method calls using jQuery promises.
  69. // Get the local file as an array buffer.
  70. var getFile = getFileBuffer();
  71. getFile.done(function (arrayBuffer) {
  72.  
  73. // Add the file to the SharePoint folder.
  74. var addFile = addFileToFolder(arrayBuffer);
  75. addFile.done(function (file, status, xhr) {
  76.  
  77. // Get the list item that corresponds to the uploaded file.
  78. var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
  79. getItem.done(function (listItem, status, xhr) {
  80.  
  81. // Change the display name and title of the list item.
  82. var changeItem = updateListItem(listItem.d.__metadata);
  83. changeItem.done(function (data, status, xhr) {
  84. alert('file uploaded and updated');
  85. });
  86. changeItem.fail(onError);
  87. });
  88. getItem.fail(onError);
  89. });
  90. addFile.fail(onError);
  91. });
  92. getFile.fail(onError);
  93.  
  94. // Get the local file as an array buffer.
  95. function getFileBuffer() {
  96. var deferred = jQuery.Deferred();
  97. var reader = new FileReader();
  98. reader.onloadend = function (e) {
  99. deferred.resolve(e.target.result);
  100. }
  101. reader.onerror = function (e) {
  102. deferred.reject(e.target.error);
  103. }
  104. reader.readAsArrayBuffer(fileInput[0].files[0]);
  105. return deferred.promise();
  106. }
  107.  
  108. // Add the file to the file collection in the Shared Documents folder.
  109. function addFileToFolder(arrayBuffer) {
  110.  
  111. // Get the file name from the file input control on the page.
  112. var parts = fileInput[0].value.split('\');
  113. var fileName = parts[parts.length - 1];
  114.  
  115. // Construct the endpoint.
  116. var fileCollectionEndpoint = String.format(
  117. "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
  118. "/add(overwrite=true, url='{2}')?@target='{3}'",
  119. appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
  120.  
  121.  
  122. // Send the request and return the response.
  123. // This call returns the SharePoint file.
  124. return jQuery.ajax({
  125. url: fileCollectionEndpoint,
  126. type: "POST",
  127. data: arrayBuffer,
  128. processData: false,
  129. headers: {
  130. "accept": "application/json;odata=verbose",
  131. "Authorization": "Bearer <?= $site->getSPAccessToken()?>",
  132. "X-RequestDigest": jQuery('#__REQUESTDIGEST').val(),
  133. "content-length": arrayBuffer.byteLength
  134. }
  135. });
  136. }
  137.  
  138. // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
  139. function getListItem(fileListItemUri) {
  140.  
  141. // Construct the endpoint.
  142. // The list item URI uses the host web, but the cross-domain call is sent to the
  143. // add-in web and specifies the host web as the context site.
  144. fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
  145. fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
  146.  
  147. var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
  148. appWebUrl, hostWebUrl);
  149.  
  150. // Send the request and return the response.
  151. return jQuery.ajax({
  152. url: listItemAllFieldsEndpoint,
  153. type: "GET",
  154. headers: {
  155. "accept": "application/json;odata=verbose",
  156. "Authorization": "Bearer <?= $site->getSPAccessToken()?>",
  157. }
  158. });
  159. }
  160.  
  161. // Change the display name and title of the list item.
  162. function updateListItem(itemMetadata) {
  163.  
  164. // Construct the endpoint.
  165. // Specify the host web as the context site.
  166. var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
  167. var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);
  168.  
  169. // Define the list item changes. Use the FileLeafRef property to change the display name.
  170. // For simplicity, also use the name as the title.
  171. // The example gets the list item type from the item's metadata, but you can also get it from the
  172. // ListItemEntityTypeFullName property of the list.
  173. var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
  174. itemMetadata.type, newName, newName);
  175.  
  176. // Send the request and return the promise.
  177. // This call does not return response content from the server.
  178. return jQuery.ajax({
  179. url: listItemEndpoint,
  180. type: "POST",
  181. data: body,
  182. headers: {
  183. "X-RequestDigest": jQuery('#__REQUESTDIGEST').val(),
  184. "Authorization": "Bearer <?= $site->getSPAccessToken()?>",
  185. "content-type": "application/json;odata=verbose",
  186. "content-length": body.length,
  187. "IF-MATCH": itemMetadata.etag,
  188. "X-HTTP-Method": "MERGE"
  189. }
  190. });
  191. }
  192. }
  193.  
  194. // Display error messages.
  195. function onError(error) {
  196. alert(error.responseText);
  197. }
  198.  
  199. // Get parameters from the query string.
  200. // For production purposes you may want to use a library to handle the query string.
  201. function getQueryStringParameter(paramToRetrieve) {
  202. var params = document.URL.split("?")[1].split("&");
  203. for (var i = 0; i < params.length; i = i + 1) {
  204. var singleParam = params[i].split("=");
  205. if (singleParam[0] == paramToRetrieve)
  206. return singleParam[1];
  207. }
  208. }
  209.  
  210. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement