Ajax File Upload with Progress Bar in Laravel 9 Example

Hello Developer, Today we are going to learn Ajax File Upload with Progress Bar in Laravel 9 Example. This tutorial will cover on how you can upload anything using ajax file upload and store the file to public directory with progress bar in Laravel 9.

This tutorial help you for learning uploading process which is now a day very important. You can change the code for you requirement. Here you will learn how you can upload file with ajax with progress bar in Laravel 9.

Steps for Ajax File Upload with Progress Bar in Laravel 9 Example

  • Step 1: Installing a fresh new Laravel 9 Application
  • Step 2: Creating Routes
  • Step 3: Creating Controllers
  • Step 4: Creating View Blade File
  • Step 5: Testing
  • Step 6: Conclusion

Also Read: Create Ajax CRUD Laravel 9 Application Example

Step 1: Installing a fresh new Laravel 9 Application

First step is to install fresh new Laravel 9 application. To install a Laravel 9 Application run the following code in terminal.

composer create-project laravel/laravel file-upload

cd file-upload

Note:file-upload” is the Laravel 9 Application name.

Installing a fresh new Laravel 9 Application
Installing a fresh new Laravel 9 Application

Also Read: How to get Country City Address from IP Address Laravel 9

Step 2: Creating Routes

Next, We are going to create two routes first, for displaying views and the second one for processing the file using jQuery to controller to upload a file.

Add the following to routes to routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FileController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::controller(FileController::class)->group(function(){
    Route::get('file-upload', 'index');
    Route::post('file-upload', 'store')->name('file.upload');
});
Adding Routes - Ajax File Upload with Progress Bar in Laravel 9 Example
Adding Routes

Step 3: Creating Controllers

Now its time to create a Controller for our application to handle the file upload and display view. Create a new file with name FileController.php inside app/Http/Controllers/ folder and add the following code into it.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class FileController extends Controller
{
    public function index()
    {
        return view('fileUpload');
    }
   
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
   
        $fileName = time().'.'.request()->file->getClientOriginalExtension();
   
        request()->file->move(public_path('files'), $fileName);
   
        return response()->json(['success'=>'You have successfully upload file.']);
    }
}
Creating Controller - Ajax File Upload with Progress Bar in Laravel 9 Example
File Controller

Also Read: Automatically Backup Database Laravel 9

Step 4: Creating View Blade File

Final step is to create a view blade file to display our form with progress bar. Create a file with name fileUpload.blade.php inside resources/views and enter the following code into it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Bootstrap 5 Progress Bar Example - LaravelTuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <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.3.0/jquery.form.min.js"></script>
</head>
<body>
    <div class="container mt-5" style="max-width: 900px">

        <div class="bg-dark p-4 text-center rounded-3 mb-2">
            <h2 class="text-white m-0">Laravel File Upload with Ajax Progress Bar Example - LaravelTuts.com</h2>
        </div> 

        <!-- Starting of successful form message -->
        <div class="row">
            <div class="col-12">
                <div class="alert alert-success success__msg bg-dark" style="display: none; color: white;" role="alert">
                    Uploaded File successfully.
                </div>
            </div>
        </div>
        <!-- Ending of successful form message -->

        <div class="card bg-transparent border rounded-3 mb-5 p-5">
            <form id="fileUploadForm" method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data">
                @csrf
                <div class="form-group mb-3">
                    <input name="file" type="file" class="form-control">
                </div>
                <div class="form-group">
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-dark" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                    </div>
                </div>
                <div class="d-grid mt-4">
                    <input type="submit" value="Upload" class="btn btn-dark">
                </div>
            </form>
        </div>

    </div>

    <script>
        $(function () {
            $(document).ready(function () {
                
                var message = $('.success__msg');

                $('#fileUploadForm').ajaxForm({
                    beforeSend: function () {
                        var percentage = '0';
                    },
                    uploadProgress: function (event, position, total, percentComplete) {
                        var percentage = percentComplete;
                        $('.progress .progress-bar').css("width", percentage+'%', function() {
                            return $(this).attr("aria-valuenow", percentage) + "%";
                        })
                    },
                    complete: function (xhr) {
                        console.log('File has uploaded');

                        message.fadeIn().removeClass('alert-danger').addClass('alert-success');
                        message.text("Uploaded File successfully.");
                        setTimeout(function () {
                            message.fadeOut();
                        }, 2000);
                        form.find('input:not([type="submit"]), textarea').val('');
                        var percentage = '0';
                    }
                });
            });
        });
    </script>
</body>
</html>

Step 5: Testing

Now, Everything is done! We are going to test the Laravel Application. First start the Laravel server by run the following command.

php artisan serve

Then open the following URL in any web browser.

http://127.0.0.1:8000/file-upload

Preview:

Testing - Ajax File Upload with Progress Bar in Laravel 9 Example

Step 6: Conclusion

Today, We had learn Ajax File Upload with Progress Bar in Laravel 9 Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: How to Create RSS Feed in Laravel 9 Example

4 Comments

Leave a Reply