本文介绍了Laravel:如何为外部文件创建下载响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经有问题 下载 文件使用Laravel,但我发现的全部内容都是处理本地文件.

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

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

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 ?

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

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.

在普通的PHP中,它类似于 .但是...

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

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

(1) How do I prepare such Laravel download response?

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

(2) How do I make sure the Laravel solution stays efficient (so, e.g. no memory leaks)?

推荐答案

类似以下的方法将起作用:

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

通过使用Symphony的 StreamedResponse

This works by using Symphony's StreamedResponse

这篇关于Laravel:如何为外部文件创建下载响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 16:45