daenufrey
2 months ago
428
7
Laravel

How to delete files on download cancellation

Posted 2 months ago by daenufrey

Hi,

Laravel is successfully deleting my temporary zip files after a full download when using the following code:

    public function downloadZip($locale, $hash) {
        $eventDate = $this->getEventDate($locale, $hash);
        $images = $this->getEventImages($eventDate);

        $zipFileName = Str::random() . '.zip';
        $this->zipImageFiles($zipFileName, $images);

        // return the file and delete it after download
        return Response::download(
            $zipFileName,
            'event-photos.zip',
            array('Content-Type: application/octet-stream','Content-Length: '. filesize($zipFileName))
        )->deleteFileAfterSend(true);
    }

However, if the user cancels the download in the browser, the file is not deleted.

Is there a way to delete the file on cancellation directly using the response? Or is there no way around a crone job deleting old files?

Thanks for your help and cheers,

Dani

Please sign in or create an account to participate in this conversation.