0
votes

I'm trying to upload a file to the SharePoint directory using the REST API and the JQuery. Reference: https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/upload-a-file-by-using-the-rest-api-and-jquery

I'm trying to run the below code from the chrome browser console.

var CreateNewList = function() {
    var fileName = "test1.txt";
    var reader = new FileReader();
    var arrayBuffer = reader.result;
    var serverUrl = "https://{site}.sharepoint.com/";
    var serverRelativeUrlToFolder = 'SampleDocuments/Folder1';
    // Construct the endpoint.
    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName); 

    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
          "accept": "application/json;odata=verbose",
          "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        }
    });
 };

String.format = function() {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i += 1) {
                var reg = new RegExp('\\{' + i + '\\}', 'gm');
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        };

The above code works fine when I run this on the SharePoint page. But the same code doesn't work when I tried from a different Web page which means the code works fine on the same domain but not on the different domain.

So, tried the other example (example 1 from the above-mentioned URL) which is to upload files across the domain.

function addFileToFolder() {
      var fileName = "test1.txt";
      var reader = new FileReader();
      var arrayBuffer = reader.result;
      var serverRelativeUrlToFolder = 'SampleDocuments/Folder1';

      var appWebUrl = "https://{site}.sharepoint.com";
      var hostWebUrl = "https://{site}.sharepoint.com";

      var fileCollectionEndpoint = String.format(
         "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
         "/add(overwrite=true, url='{2}')?@target='{3}'",
         appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);

      return jQuery.ajax({
         url: fileCollectionEndpoint,
         type: "POST",
         data: arrayBuffer,
         processData: false,
         headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
         }
      });
 }

This code doesn't work in any domain (failed in both SharePoint page and other pages) and returns 403 Forbidden error:

error:
code: "-2147024891, System.UnauthorizedAccessException"
message:
lang: "en-US"
value: "Access denied. You do not have permission to perform this action or access this resource."

I tried to get appWebUrl and hostWebUrl from the below methods, but the returned value is undefined, so just hardcoded these values in the code.

  // Get the add-in web and host web URLs.
  appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
  hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

  function getQueryStringParameter(paramToRetrieve) {
     var params =
     document.URL.split("?")[1].split("&");
     var strParams = "";
     for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
           return singleParam[1];
     }
  }

Can anyone help me to resolve this issue?

1

1 Answers

0
votes

You need know the api scenario how to use it.

The rest api works in SharePoint pages as the request will use current user authentication to access SharePoint, it won't work in a different domain page as there is no authentication.

SPAppWebUrl/SPHostUrl used in SharePoint add-in solution.

You have to follow the authentication flow to authenticate your request to access SharePoint from a different application. https://www.c-sharpcorner.com/article/access-sharepoint-online-rest-api-via-postman-with-user-context/