Laravel 在公共文件夹中下载 pdf

Ben*_*Ben 3 laravel

我在公共/下载中有 aa pdf。我只想链接到它并在浏览器中下载或打开它。我尝试http://localhost:8000/downloads/brochure.pdf在浏览器中点击,但我只是得到一个没有错误的白屏。在 Chrome DevTools > Network 中,它说请求已取消。我正在通过 javascript 插入 URL,所以我不能像这里的其他答案建议的那样使用 URL::to 或 link_to()。

注意:当我以与小册子.pdf 相同的方式链接到 css 文件时,该 css 会出现在浏览器中。

sta*_*bit 8

文件路径可以这样实现:

public function getDownload(){

        $file = public_path()."/downloads/info.pdf";
        $headers = array('Content-Type: application/pdf',);
        return Response::download($file, 'info.pdf',$headers);
    }
Run Code Online (Sandbox Code Playgroud)

函数将从:'project/public/downloads' 文件夹下载文件。

(不要忘记自己设置路由和控制器)

  • Laravel 8:返回response()->download($file, 'info.pdf', $headers); (2认同)

小智 5

假设您已将文件存储在 public 文件夹下名为 file 的文件夹下,文件名为 download.pdf,(public/file/download.pdf);

这是一个没有 Laravel 外观的最小工作替代方案。

可以将可选参数添加到->download() 方法中:https ://laravel.com/docs/9.x/responses#file-downloads

使用 php 7.4+

use Symfony\Component\HttpFoundation\BinaryFileResponse;

public function downloadPdfFile() : BinaryFileResponse
{
     return response()->download(public_path('file/download.pdf'));
}
Run Code Online (Sandbox Code Playgroud)