php 使用 Response::download 在 Laravel 中下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20415444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:10:56  来源:igfitidea点击:

Download files in laravel using Response::download

phplaravellaravel-4laravel-routing

提问by star18bit

In Laravel application I'm trying to achieve a button inside view that can allow user to download file without navigating to any other view or route Now I have two issues: (1) below function throwing

在 Laravel 应用程序中,我试图在视图中实现一个按钮,允许用户下载文件而无需导航到任何其他视图或路由 现在我有两个问题:(1)下面的函数抛出

The file "/public/download/info.pdf" does not exist

(2) Download button should not navigate user to anywhere and rather just download files on a same view, My current settings, routing a view to '/download'

(2) 下载按钮不应将用户导航到任何地方,而应仅在同一视图中下载文件,我当前的设置,将视图路由到“/下载”

Here is how Im trying to achieve:

这是我试图实现的方式:

Button:

按钮:

  <a href="/download" class="btn btn-large pull-right"><i class="icon-download-alt"> </i> Download Brochure </a>

Route :

路线 :

Route::get('/download', 'HomeController@getDownload');

Controller :

控制器 :

public function getDownload(){
        //PDF file is stored under project/public/download/info.pdf
        $file="./download/info.pdf";
        return Response::download($file);
}

回答by Anam

Try this.

尝试这个。

public function getDownload()
{
    //PDF file is stored under project/public/download/info.pdf
    $file= public_path(). "/download/info.pdf";

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

    return Response::download($file, 'filename.pdf', $headers);
}

"./download/info.pdf"will not work as you have to give full physical path.

"./download/info.pdf"将不起作用,因为您必须提供完整的物理路径。

Update 20/05/2016

更新 20/05/2016

Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Responsefacade. However, my previous answer will work for both Laravel 4 or 5. (the $headerarray structure change to associative array =>- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)

Laravel 5、5.1、5.2 或 5.* 用户可以使用以下方法代替ResponseFacade。但是,我之前的答案适用于 Laravel 4 或 5。($header数组结构更改为关联数组=>-删除“内容类型”后的冒号-如果我们不进行这些更改,则会以错误的方式添加标题: 标题的名称将是从 0,1,... 开始的数字

$headers = [
              'Content-Type' => 'application/pdf',
           ];

return response()->download($file, 'filename.pdf', $headers);

回答by DutGRIFF

File downloads are super simple in Laravel 5.

Laravel 5 中的文件下载非常简单。

As @Ashwani mentioned Laravel 5 allows file downloadswith response()->download()to return file for download. We no longer need to mess with any headers. To return a file we simply:

正如@Ashwani 提到的,Laravel 5 允许文件下载response()->download()返回文件以供下载。我们不再需要弄乱任何标题。要返回文件,我们只需:

return response()->download(public_path('file_path/from_public_dir.pdf'));

from within the controller.

从控制器内部。



Reusable Download Route/Controller

可重用的下载路由/控制器

Now let's make a reusable file download route and controller so we can server up any file in our public/filesdirectory.

现在让我们创建一个可重用的文件下载路由和控制器,以便我们可以在我们的public/files目录中提供任何文件。

Create the controller:

创建控制器:

php artisan make:controller --plain DownloadsController

Create the route in app/Http/routes.php:

在 中创建路线app/Http/routes.php

Route::get('/download/{file}', 'DownloadsController@download');

Make download method in app/Http/Controllers/DownloadsController:

使下载方法在app/Http/Controllers/DownloadsController

class DownloadsController extends Controller
{
  public function download($file_name) {
    $file_path = public_path('files/'.$file_name);
    return response()->download($file_path);
  }
}

Now simply drops some files in the public/filesdirectory and you can server them up by linking to /download/filename.ext:

现在只需将一些文件放在public/files目录中,您就可以通过链接到/download/filename.ext

<a href="/download/filename.ext">File Name</a> // update to your own "filename.ext"

If you pulled in Laravel Collective's Html packageyou can use the Html facade:

如果你拉入Laravel Collective 的 Html 包,你可以使用 Html 外观:

{!! Html::link('download/filename.ext', 'File Name') !!}

回答by sebt

In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:

在接受的答案中,对于 Laravel 4,标头数组的构造不正确。用:

$headers = array(
  'Content-Type' => 'application/pdf',
);

回答by Kirkland

Quite a few of these solutions suggest referencing the public_path() of the Laravel application in order to locate the file. Sometimes you'll want to control access to the file or offer real-time monitoring of the file. In this case, you'll want to keep the directory private and limit access by a method in a controller class. The following method should help with this:

这些解决方案中有不少建议引用 Laravel 应用程序的 public_path() 以定位文件。有时您会想要控制对文件的访问或提供对文件的实时监控。在这种情况下,您需要保持目录私有并通过控制器类中的方法限制访问。以下方法应该对此有所帮助:

public function show(Request $request, File $file) {

    // Perform validation/authentication/auditing logic on the request

    // Fire off any events or notifiations (if applicable)

    return response()->download(storage_path('app/' . $file->location));
}

There are other paths that you could use as well, described on Laravel's helper functions documentation

您也可以使用其他路径,在 Laravel 的辅助函数文档中进行了描述

回答by Ashwani Panwar

While using laravel 5use this code as you don`t need headers.

在使用laravel 5使用此代码,你不`吨需要头。

return response()->download($pathToFile);.

return response()->download($pathToFile);.

If you are using Fileentryyou can use below function for downloading.

如果您正在使用,Fileentry您可以使用以下功能进行下载。

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    $pathToFile=storage_path()."/app/".$entry->filename;
    return response()->download($pathToFile);           
}

回答by rohit ramani

// Try this to download any file. laravel 5.*

// 试试这个来下载任何文件。拉拉维尔 5.*

// you need to use facade "use Illuminate\Http\Response;"

// 你需要使用门面 "use Illuminate\Http\Response;"

public function getDownload()
{

//PDF file is stored under project/public/download/info.pdf

    $file= public_path(). "/download/info.pdf";   

    return response()->download($file);
}

回答by Ariel Ruiz

I think that you can use

我认为你可以使用

$file= public_path(). "/download/info.pdf";

$headers = array(
        'Content-Type: ' . mime_content_type( $file ),
    );

With this you be sure that is a pdf.

有了这个,你可以确定这是一个pdf。

回答by Md.Azizur Rahman

 HTML link click 
<a class="download" href="{{route('project.download',$post->id)}}">DOWNLOAD</a>


// Route

Route::group(['middleware'=>['auth']], function(){
    Route::get('file-download/{id}', 'PostController@downloadproject')->name('project.download');
});

public function downloadproject($id) {

        $book_cover = Post::where('id', $id)->firstOrFail();
        $path = public_path(). '/storage/uploads/zip/'. $book_cover->zip;
        return response()->download($path, $book_cover
            ->original_filename, ['Content-Type' => $book_cover->mime]);

    }

回答by Rishi

This is html part

这是 html 部分

 <a href="{{route('download',$details->report_id)}}" type="button" class="btn btn-primary download" data-report_id="{{$details->report_id}}" >Download</a>

This is Route :

这是路线:

Route::get('/download/{id}', 'users\UserController@getDownload')->name('download')->middleware('auth');

This is function :

这是功能:

public function getDownload(Request $request,$id)
{
                $file= public_path(). "/pdf/";  //path of your directory
                $headers = array(
                    'Content-Type: application/pdf',
                );
                 return Response::download($file.$pdfName, 'filename.pdf', $headers);      
}

回答by Atharva Kulkarni

If you want to use the JavaScript download functionality then you can also do

如果你想使用 JavaScript 下载功能,那么你也可以这样做

 <a onclick=“window.open(‘info.pdf) class="btn btn-large pull-right"><i class="icon-download-alt"> </i> Download Brochure </a>

Also remember to paste the info.pdf file in your public directory of your project

还要记住将 info.pdf 文件粘贴到项目的公共目录中