Laravel:如何为外部文件创建下载响应?

les*_*gar 6 php download laravel laravel-5.2

我知道有关于使用Laravel 下载文件的问题 ,但我发现只处理本地文件.

所以,通常情况下,我会这样做:

$path = storage_path().'/my-file.pdf';
$name = 'new-name.pdf';
$headers = '....';

return response()->download($path, $name, $headers);
Run Code Online (Sandbox Code Playgroud)

但是,当我需要下载的文件是外部文件时,我该怎么做,存放www.my-storage.net/files/123/my-file.pdf下?

我可以使用copy()函数,或者file_get_contents()和Laravel的Storage :: put()的组合,但我不想在每次下载处理时本地(和临时)存储文件.相反,我想直接通过用户的浏览器下载外部文件.

在普通的PHP中,它会是这样的.但...

(1)如何准备这样的Laravel下载响应?

(2)如何确保Laravel解决方案保持高效(例如,没有内存泄漏)?

apo*_*fos 6

像下面这样的东西会起作用:

 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\"" 
]);
Run Code Online (Sandbox Code Playgroud)

通过使用Symphony的StreamedResponse可以工作