SharePoint online: Create document using Rest API
Introduction:
Here we will discuss how we can create a document using Rest API in SharePoint Online. The sane rest api code will also work in SharePoint 2016 and SharePoint 2013.
Here in this particular example let us take a textbox, a multiple textbox as well as a button. Here user will give a name for the file and user can put the file content in the multiline textbox. Then user can submit in the button which will create a text file.
Here we will write both the html code as well as in the JavaScript object model (jsom) inside a script editor web part which will be inside a web part page. The html code will looks like below:
HTML Code:
<div id="CreateFile">
<div>
<strong>Enter Document Name:</strong>
<br />
<input type="text" id="txtDocumentTitle" />
</div>
<div>
<strong>Enter Document Content:</strong>
<br />
<textarea cols="20" id="txtDocumentContent"></textarea>
</div>
<br />
<input type="button" id="btnSubmit" value="Submit" />
</div>
<div id="divResults"></div>
Rest API Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(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('Shared Documents')/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 successfully created!");
}
function onQueryFailed() {
alert('Error!');
}
</script>
Once we will Save the page you can see a page like below where user can give a title for the file, then user can put content in the content textbox and then user can click on the submit button which will create a file inside the document library like below:
Now you can check in the document library where you can see the file got created in the document library.
References:
You can also read few useful articles below:
- SharePoint 2016 List View Auto Indexing Automatic Index Management
- Microsoft Flow Tutorials and Save my email attachments to a SharePoint document library Flow Sample
- SharePoint Branding: Displaying dynamic contents into page using JavaScript and REST API in SharePoint online or SharePoint 2016/2013
Conclusion:
Here we have disucssed how we can create a document using Rest API in SharePoint Online.