Introduction

Here we will discuss how we can work with files in SharePoint Online using JavaScript Object Model (JSOM). We will discuss how we can create a file inside the document library, read content from the file, update content into a document library and how we can delete a file from a document library. All we will see how we can do the operations using JSOM.

The same client-side code JSOM code will work in SharePoint 2013 as well as SharePoint 2016.

Create file using JSOM in SharePoint Online

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 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 a title for the document:</strong>
        <br />
        <input type="text" id="txtDocumentTitle" />
    </div>
    <div>
        <strong>Enter content for the document:</strong>
        <br />
        <textarea cols="20" id="txtDocumentContent"></textarea>
    </div>
    <br />
    <input type="button" id="btnSubmit" value="Submit" />
</div>
<div id="divResults"></div>

JSOM Code


<script>
$(function () {
    bindButtonClick();
});
function bindButtonClick() {
    $("#btnSubmit").on("click", function () {
        createDocument();
    });
}
function createDocument() {
    var docTitle = $("#txtDocumentTitle").val() + ".txt";
    var docContent = $("#txtDocumentContent").val();
    var clientContext = new SP.ClientContext();
    var oWebsite = clientContext.get_web();
    var oList = oWebsite.get_lists().getByTitle("Documents");
    var fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url(docTitle);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    for (var i = 0; i < docContent.length; i++) {
        fileCreateInfo.get_content().append(docContent.charCodeAt(i));
    }
    this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
    clientContext.load(this.newFile);
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),
    Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    $("#divResults").html("Document successfully created!");
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
}
</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.

Read file content using JSOM JSOM in SharePoint Online

Now we will see how can we read all file content using JSOM in SharePoint Online. This code works fine for SharePoint 2013 as well as in SharePoint 2016. If you want to know how we can create a file using JSOM in SharePoint online, you can see this article.

Here we have taken a button, on click on that button we will read the content of the document and will display in a div. Here we will write both html and JSOM code inside a script editor web part which we will add inside a web part page.

HTML Code


<input type="button" id="btnSubmit" value="Read Document" /><br />
<div id="divReadDocument" />

JSOM Code

Below is the JSOM code:


<script>
$(function () {
    bindButtonClick();
});
function bindButtonClick() {
    $("#btnSubmit").on("click", function () {
        readDocument();
    });
}
function readDocument() {
    var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/Shared Documents/Bijay.txt";
    $.ajax({
        url: fullUrl,
        type: "GET"
    })
    .done(function (data) {
        $("#divReadDocument").html(data);
    })
    .fail(function () {
        alert("error");
    });
}
</script>

Once you will Save the page and click on the button, you can see the .txt file content like below:

Update file content using JSOM JSOM in SharePoint Online

The we will discuss how we can update file content using JSOM JSOM in SharePoint Online. The same code will work for Office 365 SharePoint Online sites also. Before reading this article, you can check these two articles on: Steps to create file using JSOM in SharePoint Online and  How to read file content using JSOM JSOM in SharePoint Online?.

Here let us take a textbox where user can enter file name, and a multiline textbox where user can enter the content and a submit button. On click of the submit button the content will be updated in the file name given in the textbox.

Here as usual like other examples, we will write the code inside a script editor web part which we will put inside a web part page.

HTML Code

<div id="UpdateFile">
    <div>
        <strong>Document Title to Update</strong>
        <br />
        <input type="text" id="txtDocumentTitle" />
    </div>
    <div>
        <strong>Enter Update Document Content:</strong>
        <br />
        <textarea cols="20" id="txtDocumentContent"></textarea>
    </div>
    <br />
    <input type="button" id="btnSubmit" value="Update Document Content" />
</div>
<div id="divResults"></div>

JSOM Code

<script>
$(function () {
    bindButtonClick();
});
function bindButtonClick() {
    $("#btnSubmit").on("click", function () {
        createDocument();
    });
}
function createDocument() {
    var docTitle = $("#txtDocumentTitle").val() + ".txt";
    var docContent = $("#txtDocumentContent").val();
    var clientContext = new SP.ClientContext();
    var oWebsite = clientContext.get_web();
    var oList = oWebsite.get_lists().getByTitle("Documents");
    var fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url(docTitle);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    for (var i = 0; i < docContent.length; i++) {
        fileCreateInfo.get_content().append(docContent.charCodeAt(i));
        fileCreateInfo.set_overwrite(true);
    }
    this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
    clientContext.load(this.newFile);
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),
    Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    $("#divResults").html("Document updated successfully!");
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
}
</script>

 

Once you save the page, you can see the form like below, where user can give the name of the file and then the content to update. Once user click on the Update Document Content button, the document will get updated. 

Now if you will open the document library and see the file content, you can see the updated content.

Delete file from document library using JSOM JSOM in SharePoint Online

Then we will discuss how can we delete a file from document library using JSOM in SharePoint Online. The same code also works in SharePoint 2013 and SharePoint 2016.

Here in this example let us take a input textbox and a button, where user can put the file name to delete and click on the Delete File button to delete the file from the document library.

Here we will put the JavaScript and the html code inside a script editor web part which we will put inside a web part page. And in this example we are searching the file inside the Documents document library.

HTML Code


<div id="DeleteFile">
    <div>
        <strong>Enter File Name to Delete:</strong>
        <br />
        <input type="text" id="txtDocumentTitle" />
    </div>
    <br />
    <input type="button" id="btnSubmit" value="Delete File" />
</div>
<div id="divResults"></div>

JSOM Code


<script>
$(function () {
    bindButtonClick();
});
function bindButtonClick() {
    $("#btnSubmit").on("click", function () {
        deleteDocument();
    });
}
function deleteDocument() {
    var docTitle = $("#txtDocumentTitle").val() + ".txt";
    var clientContext = new SP.ClientContext();
    var oWebsite = clientContext.get_web();
    var fileUrl = _spPageContextInfo.webServerRelativeUrl + "/Shared Documents/" + docTitle;
    this.fileToDelete = oWebsite.getFileByServerRelativeUrl(fileUrl);
    this.fileToDelete.deleteObject();
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),
    Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    $("#divResults").html("Document successfully deleted!");
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
}
</script>

Once you Save the code, you can see a page like below where user can give the file name and then click on the button and on successful deletion it will display a message like below:

After this if you will go to the document library, you can not find the document becuase it has been already deleted.

References

You can see few useful articles below:

Conclusion

Here we have discussed how we can do various file operations like how we can create, read, update and delete file from SharePoint document library using JSOM.