Parse Server - How to delete image file from the server using cloud code

1.1k Views Asked by At

How can I delete an image's file from the server using Parse Cloud Code. I am using back4app.com

After Deleting Image Row

I am getting the images urls, then calling a function to delete the image using its url

Parse.Cloud.afterDelete("Image", function(request) {

    // get urls
    var imageUrl = request.object.get("image").url();
    var thumbUrl = request.object.get("thumb").url();
    if(imageUrl!=null){
        //delete
        deleteFile(imageUrl);
    }
    if(thumbUrl!=null){
        //delete
        deleteFile(thumbUrl);
    }
});

Delete the image file from the server

function deleteFile(url){

        Parse.Cloud.httpRequest({
            url: url.substring(url.lastIndexOf("/")+1),
            method: 'DELETE',
            headers: {
                'X-Parse-Application-Id': 'xxx',
                'X-Parse-Master-Key':     'xxx'
            }
        }).then(function(httpResponse) {
            console.log(httpResponse.text);
        }, function(httpResponse) {
             console.error('Request failed with response code ' + httpResponse.status);
        });
}
2

There are 2 best solutions below

2
On BEST ANSWER

for security reasons, not is posible to delete directly the image from Back4App, using DELETE from SDK or REST API. I believe that you can follow the guide below:

https://help.back4app.com/hc/en-us/articles/360002327652-How-to-delete-files-completely-

0
On

After struggling with this for a while it seems to be possible through cloud function as mentioned here. One need to use MasterKey in the cloud code:

Parse.Cloud.define('deleteGalleryPicture', async (request) => {
    const {image_id} = request.params;
    const Gallery = Parse.Object.extend('Gallery');
    const query = new Parse.Query(Gallery);
    try {
        const Image = await query.get(image_id);
        const picture = Image.get('picture');

        await picture.destroy({useMasterKey:  true});
        await Image.destroy();
        return 'Image removed.';
    } catch (error) {
        console.log(error);
        throw new Error('Error deleting image');
    }
});

For me it was first confusing since I could open the link to that file even after I deleted the reference object in the dashboard, but then I found out that the dashboard is not calling Parse.Cloud.beforeDelete() trigger for some reason.

Trying to download the data from the url after deleting the file through the cloud code function returns 0kB data and therefore confirms that they were deleted.