How to dynamically delete jpg files or all files from a SharePoint Folder

Viewed 127

I'm trying to figure out how to delete only the jpg files from a SharePoint folder (SP 2013). I am able to delete a specific .jpg file but I can't seem to be able to figure out how to delete all the jpg files.

Also I would know how to delete every file within the folder as well. I am in need of both method. I included my code with my most recent attempt to delete only the jpg files. Any help will be greatly appreciated.

$.ajax({ 
 type: "POST", 
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('/sites/dcsa/ep/epMainFiles/photoGallery/photoGalleryTest/*.jpg)/recycle()",
 
 headers: { 
     "accept": "application/json; odata=verbose", 
     "IF-MATCH": "*", 
     "X-RequestDigest": $("#__REQUESTDIGEST").val() 
 }, 

 success: function(data){ 
     alert("Document is recycled!"); 
 }, 
 error: function(error){ 
     alert("Error"); console.log(error); 
 } 

}); 
1 Answers

You could use this rest API to delete the folder.

POST https://{site_url}/_api/web/GetFolderByServerRelativeUrl('/Folder Name')
Authorization: "Bearer " + accessToken
If-Match: "{etag or *}"
X-HTTP-Method: "DELETE"
X-RequestDigest: "{form_digest_value}"

You could use the filter keyword to get all jpg file id, then delete them one by one.

/_api/web/lists/getbytitle('doc2')/Items?$select=ID,FileLeafRef&$filter=substringof('.jpg',FileLeafRef)

Delete list item rest endpoint:

POST https://{site_url}/_api/web/lists/GetByTitle('Test')/items({item_id})
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"
Content-Type: "application/json"
If-Match: "{etag or *}"
X-HTTP-Method: "DELETE"
Related