Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to create a download response for an external file?

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)?

like image 550
lesssugar Avatar asked May 23 '17 09:05

lesssugar


People also ask

How do you make a laravel file downloadable?

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.

How do I delete files after downloading in laravel?

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.


Video Answer


1 Answers

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

like image 57
apokryfos Avatar answered Sep 25 '22 01:09

apokryfos