_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

No correct solution


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

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top