【问题标题】:How to specify the extension for a downloaded file Laravel 5.0如何为下载的文件指定扩展名 Laravel 5.0
【发布时间】:2017-09-13 13:07:43
【问题描述】:

当用户点击路线时,我正在尝试下载文件,并且我能够这样做。但是,当用户想要下载 docx 或 doc 文件时,文件扩展名中没有 .doc。为了更好地问我的问题,我的代码如下:

Route::get('resumeDownload', function() {
    $user = Auth::user();
    $path = $user->cv()->first()->path; //when the user uploads a document, i store
    //the path of it in the database
    $extension = explode(".", $path)[1]; //if the user uploaded a doc, returns .doc etc
    $uploaded = Storage::get($path); //I get it from my storage
    return (new \Illuminate\Http\Response($uploaded, 200))
           ->header('Content-Type', 'application/pdf');
});

当用户想要下载 pdf 时,此代码非常有用,但是对于 .doc 文件或 .docx 文件,下载的文件没有扩展名。如果有帮助,我还保存了扩展名并可以轻松检索它。有没有办法让 .doc、.docx、.pdf 和 .txt 工作?

【问题讨论】:

    标签: php laravel file laravel-5


    【解决方案1】:

    您可以使用Content-Disposition 标头指定下载文件的名称,但无需手动创建下载响应。 Laravel 已经有一个内置的 int 函数来生成带有正确 Content-Disposition 标头的下载响应

    $headers = ['Content-Type' => 'application/pdf'];
    return response()->download($fileContent, 'filename.pdf', $headers);
    

    【讨论】:

    • 你能告诉我如何从我的代码中获取 $fileContent 吗??
    • file_get_contents($path)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2020-01-07
    相关资源
    最近更新 更多