简体   繁体   中英

Deleting files after download in laravel

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?

您可以使用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);
$filename = storage_path() . '/testing.txt';

App::finish(function($request, $response) use ($filename)
{
    unlink($filename);
});

return Response::download($filename);

Simply use this line of code:

return response()->download($file_path)->deleteFileAfterSend(true);

Here, inside download function the file path will be passed as an argument. Let's say for an example you want to backup your database in a file and also want to delete with downloading:

$date = Carbon::now()->format('Y-m-d_h-i');
$pub_path = public_path();
$file_path = $pub_path . '/application/db_backups/' . $date . '.sql';
$output = shell_exec('mysqldump -h58.84.34.65 -uwsit -pwsit97480 websms > ' . $file_path);
return response()->download($file_path)->deleteFileAfterSend(true);

如果下载后想删除源文件,直接写成如下

return response()->download($filePath)->deleteFileAfterSend(true);

For Laravel 5.8 use stream download . In the callback function, delete the file after echo the contents.

Let's take a look at the solution:


return response()->streamDownload(function () use ($pathToTheFile) {
    echo Storage::get($pathToTheFile);
    Storage::delete($pathToTheFile);
}, 'my-awesome-file-name');

I don't know if it works for the oldest or the latest versions.

unlink('./path/filename.extension');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM