Laravel 5:下载文件不显示弹出保存

Posted

技术标签:

【中文标题】Laravel 5:下载文件不显示弹出保存【英文标题】:Laravel 5: Download file not show popup for save 【发布时间】:2016-12-20 12:16:20 【问题描述】:

在我的 Laravel 5.3 中,我将文件上传到“uploads/files/file.pdf”。当我尝试下载它时,使用“file_exists”功能找到该文件,但没有弹出窗口将文件保存到本地计算机。注意:我通过将文件移动到名为“local”的子目录从 url 中删除了“public”文件夹。

请指教出了什么问题。

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use Response;

...............................

public function getDownload()

    $file= "uploads/files/file.pdf";

    echo $file;

    if(file_exists($file))
        dd('File is exists.');
    else
        dd('File is not exists.');
            

    $headers = array('Content-Type: application/pdf',);
    return Response::download($file, 'filename.pdf', $headers);

【问题讨论】:

清除浏览器缓存后重试 试试$file = public_path() . "/uploads/files/file.pdf"; 【参考方案1】:

我认为您还需要一个标题来告诉浏览器打开文件或下载文件。

所以要在浏览器中下载它使用

header('Content-Disposition: attachment; filename="filename.pdf"');

要在浏览器中打开它,请使用

header("Content-Disposition: inline; filename=filename.pdf");

在你的例子中你应该有你的 $header 变量像

$headers = array('Content-Type: application/pdf','Content-Disposition: inline; filename=filename.pdf');

$headers = array('Content-Type: application/pdf','Content-Disposition: attachment; filename="filename.pdf"');

我个人像下面这样使用它

header("Content-type: application/pdf");
header("Content-Length:" . strlen($file));
//header("Content-Disposition: inline; filename=file.pdf");
header('Content-Disposition: attachment; filename="file.pdf"');
print $file;

或者也许只是在你的情况下这样做

return response()->download("uploads/files/file.pdf");

整个控制器代码如下

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use Response;

...............................

public function getDownload()

    $file= "uploads/files/file.pdf";

    //echo $file;

    if(file_exists($file))
        //dd('File is exists.');
        return response()->download($file);

    else
        //dd('File is not exists.');
        abort(404);
      

【讨论】:

我使用了它们中的每一个,但仍然无法正常工作。 $headers = array('Content-Type: application/pdf','Content-Disposition: attachment; filename="filename.pdf"'); return Response::download($file, 'filename.pdf', $headers); @Naren 我已经更新了关于我如何做到这一点的答案。您是否尝试过可能只是return response()->download($pathToFile);return response()->download($pathToFile, $name, $headers); 还是不行。你能写出完整的Controller和函数吗? 现在已修复。我使用 barryvdh/laravel-dompdf 从视图中生成 pdf 并保存。谢谢大家的回答。 @Naren 如果这对您有所帮助,请接受它作为答案。如果您有自己的解决方案,请提供进一步使用。

以上是关于Laravel 5:下载文件不显示弹出保存的主要内容,如果未能解决你的问题,请参考以下文章

Laravel - 在存储中显示 PDF 文件而不强制下载?

Laravel - 在存储中显示 PDF 文件而不强制下载?

java下载文件,怎么指定下载到指定的文件夹下啊,就是不弹出保存框,直接下载到指定的文件夹下,谢谢回答

ASP.NET 中,实现download下载,弹出打开和保存对话框,不限制文件大小,跪求实现代码,谢谢了

Laravel 5.4 下载 csv 文件不起作用

Laravel 5.3 保护下载文件的正确方法