Sp-dev-docs: Can't delete file with REST API

Created on 10 Sep 2020  路  4Comments  路  Source: SharePoint/sp-dev-docs

Category

  • [x ] Question
  • [ ] Typo
  • [ ] Additional article idea

Question

I Can't delete file via REST API.

I tried delete file on sharepoint with REST API. but i get this response

Methode:post -> https://{siteUrl}/_api/Web/GetFolderByServerRelativeUrl('InterfaceFiles/Employee/myFile.pdf')

Header:
 Cookie : {myCookie},
 Accept: application/json;odata=verbose,
 Content-Type: application/json;odata=verbose,
 X-RequestDigest: {myDigest},
 IF-MATCH: '*',
 X-HTTP-Method:"DELETE"

```json
{
"error": {
"code": "-2130575251, System.Runtime.InteropServices.COMException",
"message": {
"lang": "en-US",
"value": "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."
}
}
}

#### I have tried follow official docs but not work
[Official Documents](https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest#working-with-files-by-using-rest)
#### And i have tried this way. **but not working.**
```config
Methode:delete -> https://{siteUrl}/_api/Web/GetFolderByServerRelativeUrl('InterfaceFiles/Employee/myFile.pdf')
or
Methode:delete -> https://{siteUrl}/_api/Web/GetFolderByServerRelativeUrl('InterfaceFiles/Employee/')/Files('myFile.pdf')
or
Methode:delete -> https://{siteUrl}/_api/Web/GetFolderByServerRelativeUrl('InterfaceFiles/Employee/myFile.pdf')/recycle

Headers:
   "Cookie", {myToken}
   "accept", "application/json;odata=verbose"
   "content-type", "application/json;odata=verbose"
   "X-RequestDigest", {myDigest}
   "IF-MATCH", "*"

but i tried read file by this method. but work for me.

Methode:delete -> https://{siteUrl}/_api/Web/GetFolderByServerRelativeUrl('InterfaceFiles/Employee/')/Files('myFile.pdf')/$value
**The headers  same as above**

all method in description not working for me :(

csorest question

Most helpful comment

@i3irdodds,
Yes, the error message in the original post is because of the invalid form digest value.
In the page, can use $("#__REQUESTDIGEST").val() get the current site form digest value also :-)

All 4 comments

Thank you for reporting this issue. We will be triaging your incoming issue as soon as possible.

Here is a sample code to delete specific file in the SharePoint default Documents library:

<script type="text/javascript">
DeleteFile();

function DeleteFile() {

    var WebServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl;

    // Provide Internal name of the library here
    var DocuentLibraryInternalName = "Shared%20Documents";

    // Provide name of the document
    var DocumentName = "test.pdf";

    var ServerRelativeUrlofFile = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + WebServerRelativeUrl + "/" + DocuentLibraryInternalName + "/" + DocumentName + "')"

    $.ajax
        ({
            // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
            // You can replace this with other site URL where you want to apply the function

            url: ServerRelativeUrlofFile,
            type: "POST",
            headers:
        {
            // Accept header: Specifies the format for response data from the server.
            "Accept": "application/json;odata=verbose",
            //Content-Type header: Specifies the format of the data that the client is sending to the server
            "Content-Type": "application/json;odata=verbose",
            // IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
            // "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
            "IF-MATCH": "*",
            //X-HTTP-Method:  The MERGE method updates only the properties of the entity , while the PUT method replaces the existing entity with a new one that you supply in the body of the POST
            "X-HTTP-Method": "DELETE",
            // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
            success: function (data, status, xhr) {
                console.log("Success");
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });
}
</script>

Reference:
Delete File in SharePoint using REST API

@Jerry0527 Thank you.
Now I understand that the problem is caused by RequestDigest Can not be used. Because I got it from a request from another site.

My solution is request page for get context and find formDigestValue value in

@i3irdodds,
Yes, the error message in the original post is because of the invalid form digest value.
In the page, can use $("#__REQUESTDIGEST").val() get the current site form digest value also :-)

Was this page helpful?
0 / 5 - 0 ratings