Laravel Ajax File Upload With Progress Bar Example Tutorial

May 08, 2024 | jQuery Ajax Laravel 11 Laravel


Hello Dev,

In this tutorial, we'll explore how to implement Ajax image upload with a progress bar in a Laravel 11 application.

Typically, file uploads are straightforward, but when dealing with large file sizes, the upload process can take some time. While you can't necessarily speed up the upload process, you can enhance the user experience by displaying a progress bar, indicating the upload progress to the client.

Here are the steps we'll follow:

1. Define two routes in Laravel, associated with the FileController controller.
2. Implement a jQuery AJAX method triggered upon clicking the submit button.
3. Display a progress bar to visualize the upload progress.

By following these steps, users will have a better understanding of how long it will take to upload a file or image. Let's dive into the implementation.

To implement AJAX image upload with a progress bar in a Laravel 11 application, follow these steps:

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel example-app
Read Also: Jquery Email Address Autocomplete Example Tutorial Step 2: Create Routes

Add two new routes in your routes/web.php file. One for displaying the form and another for handling the file upload.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileController;

Route::get('/file-upload', [FileController::class, 'index'])->name('file.index');
Route::post('/file-upload', [FileController::class, 'store'])->name('file.store');
Step 3: Create FileController

Generate a new controller named FileController if you haven't already.

php artisan make:controller FileController

Then, add the index and store methods to handle the view and file upload logic.

app/Http/Controllers/FileController.php
<?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 uploaded the file.']);
    }
}
Read Also: Bootstrap Input Multiple Values Textbox Plugin Step 4: Create Blade File

Create a new Blade file named fileUpload.blade.php in your resources/views directory. This file will contain the HTML form for file upload and the JavaScript for handling the AJAX request and updating the progress bar.

resources/views/fileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Ajax File Upload With Progress Bar Example Tutorial -- ItErrorSolution.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5" style="max-width: 900px">
        <div class="alert alert-primary mb-4 text-center">
            <h2 class="display-6">Laravel Ajax File Upload With Progress Bar Example Tutorial -- ItErrorSolution.com</h2>
        </div>  
        <form id="fileUploadForm" method="POST" action="{{ route('file.store') }}" 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-success" 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="Submit" class="btn btn-primary">
            </div>
        </form>
    </div>
    <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>
    <script>
        $(function () {
            $(document).ready(function () {
                $('#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) {
                        alert('File has uploaded successfully!');
                    }
                });
            });
        });
    </script>
</body>
</html>
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/file-upload

This setup uses Bootstrap for styling and jQuery along with the jquery.form plugin to handle the AJAX file upload and update the progress bar accordingly.

Output: Laravel Ajax File Upload With ProgressLaravel Ajax File Upload With Progress Bar Example Tutorial Bar Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#jQuery
#Ajax
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"