I'm creating a application that lets a user download a file. After the download i want the file to be deleted. The end of my code is like this:
return Response::download(public_path() . '/uploads/_tmp/' . urldecode($filename));
which means that the function ends on the return an i am not able to delete the file. I have tried to call a 'after' filter on the route but then the file gets deleted to quickly.
Any ideas?
You could use PHP's unlink() method just as @Khan suggested. But if you want to do it the Laravel way, use the File::delete() method instead. $files = array($file1, $file2); File::delete($files);
One way to delete a file from the public directory in Laravel is to use the Storage facade. To delete a file, you will need to follow the following steps: Step 1: Check to ensure that the folder and file exist. Step 2: Delete the required file.
The deleteDirectory() method from File Facade is used to delete a folder. The files along with the folder are completely removed by this method.
You can use deleteFileAfterSend
http://laravel.com/docs/5.0/responses#other-responses
return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
I personally use the following;
$response = Response::make(file_get_contents($path_to_file), $status_code, $headers);
Status code is obviously the code which you want to return.
Within the $header parameter you can pass an array with the indexes Content-Type and Content-Disposition.
Then you can simply unlink $path_to_file and return $response.
Much easier way of deleting a file would be to use Jon's answer for versions of Laravel > 4.0.
You can use deleteFileAfterSend
http://laravel.com/docs/5.0/responses#other-responses
return response()->download($filePath, $fileName, $headers)->deleteFileAfterSend(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With