[php] Download files in laravel using Response::download

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

This question is related to php laravel laravel-4 laravel-routing

The answer is


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');

 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]);

    }

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

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

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

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') !!}

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


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.


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

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

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


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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to laravel-routing

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile] Laravel: How to Get Current Route Name? (v5 ... v7) Set session variable in laravel Laravel 5 - redirect to HTTPS How Can I Remove “public/index.php” in the URL Generated Laravel? Download files in laravel using Response::download Laravel Controller Subfolder routing My Routes are Returning a 404, How can I Fix Them?