'api platform: delete a file after handling

I followed the documentation to upload files to my public folder, and now I wish I could delete a file from that folder.

if I use the query provided by api platform: api/image/{id} I can only delete the row in my table. I would already have to retrieve the path of the image to save it in the table. And maybe then I can use it to delete the image?

I need a Deserializer ?

Laurent.



Solution 1:[1]

You need to create an EventListener and listen to the postRemove event so that after deleting an entry from the Image entity, you physically remove the file from the directory.

An example of listening for events on an Image entity:

class ImageEventSubscriber
{
 
    public function postRemove(Image $image, LifecycleEventArgs $event){

        $image_path =  $image->getPath(); // You may have to specify the full path to the file if it is not listed in the database.

        if (file_exists($image_path))
        {
            unlink($image_path);
        }

    }
}

Now you need to declare your event listener in the services.yaml file

  App\EventListener\ImageEventSubscriber: 
    tags: [ { name: doctrine.orm.entity_listener, entity: App\Entity\Image, event: postRemove } ]

Now, when requesting DELETE: api/image/{id}, the record and file will be deleted. You can get more information about EventSubscriber by reading the documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harvey Dent