Deleting a File from Storage after Download in Laravel
Let's assume you have a file in storage/app/download.zip
:
Because Laravel uses Symfony's HttpFoundation internally, you can use the deleteFileAfterSend
method:
public function download()
{
return response()
->download(storage_path('app/download.zip'))
->deleteFileAfterSend(true);
}
or you can create a Terminable Middleware that deletes the file after the download response was prepared.
class StorageDownload
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
\Storage::delete('download.zip');
}
}
As for triggering the download using JavaScript, something as trivial as setting the window location will work:
axios.post('files/export/' + file.id, formData)
.then(function() {
window.location = 'files/download/' + file.id
});
Don't worry, this will not navigate away from your current page, it will just trigger the download.