Download files in laravel using Response::download
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);
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') !!}
In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:
$headers = array(
'Content-Type' => 'application/pdf',
);