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

时间:2017-05-23 09:41:22

标签: php laravel download laravel-5.2

我知道Laravel已经有questions about downloading files,但我发现只能处理本地文件。

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

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

return response()->download($path, $name, $headers);

当我需要下载的文件是外部时,我该怎么办,位于 www.my-storage.net/files/123/my-file.pdf

我可以使用copy()功能,或file_get_contents()和Laravel Storage::put()的组合,但我不想在本地存储文件(每次下载时都会暂时)。相反,我想直接通过用户的浏览器下载外部文件。

在普通的PHP中,它会像 this 。但...

(1)如何准备此类Laravel下载响应?

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

1 个答案:

答案 0 :(得分:4)

以下内容可行:

 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\"" 
]);

这可以通过使用Symphony的StreamedResponse

来实现