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

I know there have already been questions about uploading files with Laravel, but everything I've found deals 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 should I do when the file I need to upload is external , putting it 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 it locally locally (and temporarily) every time a download is processed. Instead, I want to download an external file directly through the user's browser.

In simple PHP, it would be something like this . But...

(1) How to prepare a response like this for a Laravel download?

(2) How can I make sure the Laravel solution stays efficient (like memory leaks)?

+3


source to share


2 answers


The following will 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 using Symphony StreamedResponse

+2


source


you can pass a full link to the file like www.dsa.com/sad.pdf to the balde file and

then



<a href="{{ link_of_file }}" download=download>Download File </a>

      

it will download the file to the user's computer directly

+1


source







All Articles