_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)"; 
({ 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

  • Is there any error? – Ganesh Sanap Jun 29 at 15:48
  • No error. It just doesn't work. – Ben Segarra Jun 30 at 18:29

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"
    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, privacy policy and cookie policy

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