我的控制器中有这个方法,我在其中调用返回 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']);
如果我这样做
return response()->file($file)
,它会抛出错误:
Symfony \ 组件\ HttpFoundation\ 文件 \ 异常\ FileNotFoundException
有什么方法可以实现而无需先存储文件吗?
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');
我面临着同样的问题,但我需要直接在用户的浏览器中显示它,而不是提示下载。
所以这就是我的处理方式:
$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);