1
_spPageContextInfo.webAbsoluteUrl + "_api/web/getfolderbyserverrelativeurl('/s/KM/box/pg/testRestDocs')/Files/add(url='" + docTitle + "',overwrite=true)";

$(function () { bindButtonClick(); }); function bindButtonClick() 
{ $("#btnSubmit").on("click", function () { createDocument(); }); 
} function createDocument() { var docTitle = $("#txtDocumentTitle").val() + ".txt"; var docContent = $("#txtDocumentContent").val(); 
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "_api/web/getfolderbyserverrelativeurl('/s/KM/box/pg/testRestDocs')/Files/add(url='" + docTitle + "',overwrite=true)"; 
$.ajax
({ url: fullUrl, 
  type: "POST", 
  data: docContent,
   headers: { "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose",
     "X-RequestDigest": $("#__REQUESTDIGEST").val() },
      success: onQuerySucceeded, error: onQueryFailed }); 
    } 
    function onQuerySucceeded() { $("#divResults").html("Document created!"); }
     function onQueryFailed() { alert('Error!'); }

My code fails to create a file

2

1 Answer 1

1

I’m going to assume you get an error in the console when the button is clicked.

You are missing the Authorization header with the Authz access token

This example taken from: Working with folders and files with REST

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)
method: POST
body: "Contents of file"
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-length:length of post body

All write operations require the authorization token in SharePoint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.