Today’s tutorial I will show you how to work on ajax file upload with progress bar in Laravel. File uploads are pretty much everywhere in today’s web/mobile applications. For example, in Facebook profile users want to add a photo, or in twitter handle users want to show an event picture etc.
Let’s start with create our own image upload script with progress bar. So this application utilizes the Jquery form library to upload the file to our server. This tutorial guides you through the steps to do ajax file upload with a progress bar.
Step 1 : Install Laravel application
Run the below command to install laravel in your server or local machine.
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Configure the .env
We will add our database details to .env
file which holds the environment specific values in our application.
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=<your_db_name> DB_USERNAME=<your_db_username> DB_PASSWORD=<your_db_password>
Step 3 : Create controller
We will create our controller that hosts the code to upload and save the file via ajax. Run the below command to create the controller and copy paste the below code to it.
php artisan make:controller BlogController
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Blog; class BlogController extends Controller { public function index() { return view('fileupload_form'); } public function store(Request $request) { $title = "Sample Title"; $filename = time().'.'.request()->file->getClientOriginalExtension(); $request->file->move(public_path('blogs'), $filename); $blog = new Blog; $blog->title = $title; $blog->image = $filename; $blog->save(); return response()->json(['success'=>'Image Uploaded Successfully']); } }
Step 4: Create Migration & Model
Run the below command to generate the migration file and model for application. You may have noticed that -m
at the end of the command, that will create a migration file too when the model created.
php artisan make:model Blog -m
In your migration file, add the below lines in the up() function.
public function up() { Schema::create('blogs', function (Blueprint $table) { $table->id(); $table->string('title', 255); $table->string('image', 255); $table->timestamps(); }); }
After that run the below command to generate the necessary tables in your database. This command create table named blogs the database.
php artisan migrate
Step 5: Add routes to web.php
Next add get and post routes to the routes/web.php file in our application.
Route::get('ajax-file-upload', '\App\Http\Controllers\BlogController@index'); Route::post('store', '\App\Http\Controllers\BlogController@store');
Step 6: Create Blade View
Next, we will create our blade file that will be holding the HTMl elements for our example. This view file consists of several HTML elements to work the file upload and upload progress. Create the file in the following folder resources/views/fileupload_form.blade.php
and copy paste the below content.
<!DOCTYPE html> <html> <head> <title>Laravel Ajax File Upload with Progress Bar</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script> <style> .progress { position:relative; width:100%; } .bar { background-color: #00ff00; width:0%; height:20px; } .percent { position:absolute; display:inline-block; left:50%; color: #040608;} </style> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-8 offset-md-2"> <div class="card"> <div class="card-header text-center"> <h4>Laravel Ajax File Upload with Progress Bar</h4> </div> <div class="card-body"> <form method="POST" action="{{ url('store') }}" enctype="multipart/form-data"> @csrf <div class="form-group"> <input name="file" type="file" class="form-control"><br/> <div class="progress"> <div class="bar"></div > <div class="percent">0%</div > </div> <br> <input type="submit" value="Submit" class="btn btn-primary"> </div> </form> </div> </div> </div> </div> </div> <script type="text/javascript"> $(function() { $(document).ready(function() { var bar = $('.bar'); var percent = $('.percent'); $('form').ajaxForm({ beforeSend: function() { var percentVal = '0%'; bar.width(percentVal) percent.html(percentVal); }, uploadProgress: function(event, position, total, percentComplete) { var percentVal = percentComplete + '%'; bar.width(percentVal) percent.html(percentVal); }, complete: function(xhr) { alert('File Has Been Uploaded Successfully'); } }); }); }); </script> </body> </html>
By this step , you are done with the programming of the Laravel file uploader, next we will test the application.
Step 7: Run the application
You can run the application by visiting the application url in browser like below.
http://localhost/ajax-file-upload
You might interested the other Laravel tutorials
Hierarchical Tree view Category Example in Laravel
Laravel 8 Create Custom Helper Functions (Global function)
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Dev says
Doesn’t work as shown.
Editorial Staff says
Could you please share the error you are getting?