0

Is there a way I could remove all files from given folder using SharePoint REST api?

0

You can use SPServices Batch operation to delete all the files from a given folder. You can loop through each item/file inside a folder and create a batch like this:

Assume you have looped through all the list item and saved in an array filesToBeDeleted[];

var batchCmd = "<Batch OnError='Continue'>";
for(var i=1;i<=filesToBeDeleted.length;i++)
{
 batchCmd = batchCmd + "<Method ID=+i+ Cmd='Delete'><Field Name='ID'>" + 
 filesToBeDeleted["itemID"] + "</Field><Field Name='FileRef'>" + 
 filesToBeDeleted["fileRef"] + "</Field></Method>"
}
batchCmd = batchCmd + "</Batch>";

Make sure all the information related to every file must be included in batchCmd variable. once you are done with creating batch, simply run this SPService call to delete all of them in one shot.

    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        listName: listName,
        updates: batchCmd,
        completefunc: function ( xData, Status ) {          
            $( xData.responseXML ).SPFilterNode( 'ErrorCode' ).each( function(){
                responseError = $( this ).text();               
                if ( responseError === '0x00000000' ) {
                    alert( "All the files have been successfully deleted." );
                }   
                else {
                    alert( "There was an error trying to delete the file." );
                }
            });
        }
    }); 

Edit1: In case of REST call, You have to make one call for for every single file. Refer the end-point--

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name')
method: POST
headers:
    Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    IF-MATCH: etag or "*"
    X-HTTP-Method:"DELETE"
0

Delete folder in one go:

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')
method: POST
Headers: 
 Authorization: "Bearer " + accessToken
 X-RequestDigest: form digest value
"IF-MATCH": etag or "*"
"X-HTTP-Method":"DELETE"
  • This will delete the complete folder itself. It is mentioned in question that only the files must be deleted from the folder. – DvG Jul 9 '18 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.