107

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

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'

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);
}
DPP
  • 12,716
  • 3
  • 49
  • 46

12 Answers12

216

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.

Update 20/05/2016

Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response facade. However, my previous answer will work for both Laravel 4 or 5. (the $header array 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,...)

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

return response()->download($file, 'filename.pdf', $headers);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Anam
  • 11,999
  • 9
  • 49
  • 63
53

File downloads are super simple in Laravel 5.

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

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/files directory.

Create the controller:

php artisan make:controller --plain DownloadsController

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

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

Make download method in 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/files directory and you can server them up by linking to /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 package you can use the Html facade:

{!! Html::link('download/filename.ext', 'File Name') !!}
DutGRIFF
  • 5,103
  • 1
  • 33
  • 42
  • Worked like a charm, Thanks a lot @DutGRIFF, You saved my day. I tried this download thing for 5 hours but didn't work though, I didn't get any solution but when I tried your solution it worked like a charm. Laravel rocks. – Prasad Patel May 20 '17 at 06:12
  • this is the perfect code ! works like charming! – Faiyaj Nov 23 '21 at 13:18
30

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

$headers = array(
  'Content-Type' => 'application/pdf',
);
sebt
  • 2,254
  • 2
  • 14
  • 11
  • the difference in the instantiation of the array is likely because of a PHP version, not laravel version ;) – ShaneMit Sep 29 '17 at 20:07
11

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:

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

Kirkland
  • 798
  • 1
  • 8
  • 20
8

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

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

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

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    $pathToFile=storage_path()."/app/".$entry->filename;
    return response()->download($pathToFile);           
}
Ashwani Panwar
  • 3,819
  • 3
  • 46
  • 66
  • 2
    This answer would be helpful if it left out the unnecessary parts or even just expanded on them below the pure answer. `Fileentry` is a different feature not needed for this question. Edit answer and I will upvote because the mentioning of LV5s `response()->download()`. – DutGRIFF Jan 26 '16 at 16:04
8

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.

Ariel Ruiz
  • 163
  • 2
  • 6
8

HTML href link click:

<a ="{{ route('download',$name->file) }}"> Download  </a>

In controller:

public function download($file){
    $file_path = public_path('uploads/cv/'.$file);
    return response()->download( $file_path);
}

In route:

Route::get('/download/{file}','Controller@download')->name('download');
Patryk Uszyński
  • 1,069
  • 1
  • 12
  • 20
aminul
  • 81
  • 1
  • 2
3

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

// you need to use facade "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);
}
Rohit Ramani
  • 776
  • 7
  • 15
2
 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]);

    }
0

This is html part

 <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);      
}
0

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

 <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

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
0

you can use simply inside your controller: return response()->download($filePath); Happy coding :)

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38