I know there have already been questions about downloading files with Laravel, but all I found deal with local files.
So, normally, I would do something like this:
$path = storage_path().'/my-file.pdf';
$name = 'new-name.pdf';
$headers = '....';
return response()->download($path, $name, $headers);
But what do I do, when the file I need to download is external, laying under www.my-storage.net/files/123/my-file.pdf ?
I could use the copy() function, or a combination of file_get_contents() and Laravel's Storage::put(), but I don't want to store the file locally (and temporarily) every time a download is being processed. Instead, I want to download the external file directly via user's browser.
In plain PHP, it would be something like this. But...
(1) How do I prepare such Laravel download response?
(2) How do I make sure the Laravel solution stays efficient (so, e.g. no memory leaks)?
Downloading files in Laravel is even more simple than uploading. You can pass download() method with file path to download file. Same way, if you want to download file from the public folder, you can use download() method from Response class.
Just place it in the controller instead of the app/start/global. php." DeleteFileAfterSend(true) works great on Laravel 5.3 as well. Although the documentation doesn't state anything about it, you can still use it.
Something like the following would work:
return response()->stream(function () {
//Can add logic to chunk the file here if you want but the point is to stream data
readfile("remote file");
},200, [ "Content-Type" => "application/pdf",
"Content-Length" => "optionally add this if you know it",
"Content-Disposition" => "attachment; filename=\"filename.pdf\""
]);
This works by using Symphony's StreamedResponse
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