首页 > 解决方案 > 强制浏览器下载通过 PHP/Laravel 中的外部 URL 检索到的文件

问题描述

我已经坚持了几个小时。也许我的心已经累了。我希望有人可以帮助我。我正在开发一个连接到创建和编辑发票的外部应用程序的 Laravel 应用程序。我的一条路线应该允许用户从此外部应用程序下载 PDF 发票。我的控制器类似于下面的代码:

public function download(Invoice $invoice)
{
    // Creates an instance of the remote invoice
    $remoteInvoiceFile = RemoteInvoiceSoftware::find($invoice->id);

    return response()->streamDownload(function () use ($remoteInvoiceFile ) {
        // This calls the remote server and the server responds with the PDF file contents
        $file = $remoteInvoiceFile->download();

        echo $file;
    }, 'file.pdf');
}

streamDownoad从 Laravel 文档中阅读了有关该功能的信息,并以与显示相同的方式实现了它。但是我在可以下载 PDF 文件时遇到错误,但是,不仅文件小于 5KB(原始发票文件约为 60KB),当我尝试打开它时也会出现错误。关于文件损坏或解析不正确的一些事情。

当我echo $remoteInvoiceFile->download()不使用时,streamDownload我会得到这样的结果:

当我回显来自发票 URL 的响应内容时

请帮我弄清楚发生了什么以及如何解决这个问题。谢谢!!

标签: phplaravellaravel-5responseresponse-headers

解决方案


推荐阅读