How do I download files using Laravel PHP?
Last updated Jan 19, 2022File uploading and download are typical and crucial features in online applications. Using Laravel, we'll show you how to get files from the public folder and download files using laravel.
How to download files from the Public storage folder in Laravel
The steps below illustrate how you can easily download files from the public storage folder and display files on the Laravel blade views:
Step 1: First, create a new Laravel application using the following command
composer create-project --prefer-dist laravel/laravel download |
Step 2: Open your Routes/web.php file and add the following code:
use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group that | contains the "web" middleware group. Now create something great! | */
Route::get('/', function () { return view('welcome'); }); Route::get('view', 'FileController@view'); Route::get('get/{filename}', 'FileController@getFile')->name('getfile'); |
Step 3: Now, run the command php artisan make: controller FileController to create a new Controller file FileController.php In your app/controllers
Now open your FileController.php and add the following methods
function getFile($filename){ $file=Storage::disk('public')->get($filename); return (new Response($file, 200)) ->header('Content-Type', 'image/jpeg'); } |
This code will download files from the public storage by giving the files and returning the response and correcting the content type.
To display files on blade views, then update the following methods in your controller file
$files = Storage::files("public"); $images=array(); foreach ($files as $key => $value) { $value= str_replace("public/","",$value); array_push($images,$value); } return view('show', ['images' => $images]); |
This code will get the image files from the public storage folder and extract the name of the files and pass them to the view files.
Step 4: Now create the Blade view, show.blade.php in your resources\view folder. Open your show.blade.php and paste the code below
Download files here from storage folder
@foreach($images as $image)
<`img src="{{route('getfile', $image)}}`" />
@endforeach |
Step 5: We are done. Now you can download your pdf and image files from your public folder
![]() |
Conclusion: In this laravel tutorial example we covered how to download files php
Article Contributed By :
|
|
|
|
1400 Views |