Introduction:

In this post we will discuss how we can delete file from document library using Rest API in SharePoint Online Office 365. Here in this example we have a file name as Bijay.txt inside the documents document library. We will delete the file using Rest API. The same code will work for both SharePoint 2016 and SharePoint 2013.

The document library looks like below:



Here we have taken a html input box and a submit button. User will give a name in the textbox and click on the Delete File button which will delete the file from the document library.

Below is the HTML Code:

Here let us add both the html and Rest API code inside a script editor web part inside a web part page.

HTML Code:

<div id="DeleteFile">

    <div>

        <strong>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>

Below are the Rest API code. Here we are calling the deleteDocument() method on the button click. 

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 () {

        deleteDocument();

    });

}

function deleteDocument() {

    var docTitle = $("#txtDocumentTitle").val() + ".txt";

    var siteUrl = _spPageContextInfo.webAbsoluteUrl;

    var webRelUrl = _spPageContextInfo.webServerRelativeUrl;

    var fullUrl = siteUrl + "/_api/web/GetFileByServerRelativeUrl('" + webRelUrl +"/Shared Documents/" + docTitle +

    "')";

    $.ajax({

        url: fullUrl,

        type: "POST",

        headers: {

            "accept": "application/json;odata=verbose",

            "content-type": "application/json;odata=verbose",

            "X-RequestDigest": $("#__REQUESTDIGEST").val(),

            "X-HTTP-Method": "DELETE",

            "IF-MATCH": "*"

        },

        success: onQuerySucceeded,

        error: onQueryFailed

    });

}

function onQuerySucceeded() {

    $("#divResults").html("Document successfully deleted!");

}

function onQueryFailed(sender, args) {

    alert('Error!');

}

</script>

Once you Save the code and refresh the page, then you can see the page will appear like below, where user can give the file name and click on the Delete File button which will delete the file from the document library.



Now if we will check the document library the file is not there like below:



References:

Also you can read some useful articles:

Conclusion:

Here we have discussed how we can delete a file from document library using Rest API in SharePoint Online Office 365 site.