从 Laravel 中的外部 API 调用返回文件响应

问题描述 投票:0回答:2

我的控制器中有这个方法,我在其中调用返回 PDF 文件的外部 URL:

public function get()
{
    $response = Http::withHeaders(['Content-Type' => 'application/pdf'])
      ->get('https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf')
      ->body();

    return $response;
}

routes/api.php

Route::get('/file', [FileController::class, 'get']);

在浏览器中调用该路由会显示此乱码输出而不是实际文件: enter image description here

如果我这样做

return response()->file($file)
,它会抛出错误:

Symfony \ 组件\ HttpFoundation\ 文件 \ 异常\ FileNotFoundException

有什么方法可以实现而无需先存储文件吗?

php laravel
2个回答
3
投票

要发送文件响应而不在本地存储文件,您可以使用

streamDownload
:

return response()->streamDownload(function () {
    echo Http::withHeaders(['Content-Type' => 'application/pdf'])
      ->get('https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf')
      ->body();
}, 'c4611_sample_explain.pdf');

0
投票

我面临着同样的问题,但我需要直接在用户的浏览器中显示它,而不是提示下载。

所以这就是我的处理方式:

$body = Http::withHeaders(['Content-Type' => 'application/pdf'])
  ->get('https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf')
  ->body();

$headers = [
        "Content-type" => "application/pdf",
        "Content-Disposition" => "inline; filename=the-file.pdf",
        "Access-Control-Expose-Headers" => "Content-Disposition",
        "Pragma" => "no-cache",
        "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
        "Expires" => "0"
    ];

return response()->stream(function() use($body){
        $file = fopen('php://output', 'w');
        fwrite($file, $body);
        fclose($file);
    }, 200, $headers);
© www.soinside.com 2019 - 2024. All rights reserved.