Home Ajax How To File Upload with Progress Bar In Laravel 9 Ajax ?

How To File Upload with Progress Bar In Laravel 9 Ajax ?

by Shahriar Sagor

Hello Dev, Today now in this post i will show you Laravel 9 Ajax File Upload with Progress Bar. If you want to know about Laravel 9 Ajax File Upload with Progress Bar then i hope you are in right place. Here i will show this example step by step.

This is very basic example of Laravel 9 Ajax File Upload with Progress Bar. Here I will give a simple example with a solution.

Let’s start and see the bellow example:-

Step 1: Install Laravel

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel example-app
Step 2: Create Routes

Now in this step, i will be add new two routes. One for the display view and i will write jquery code in view file. Then in the Second step, i will create POST route for file upload.

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::controller(FileController::class)->group(function(){
    Route::get('file-upload', 'index');
    Route::post('file-upload', 'store')->name('file.upload');
});
Step 3: Create FileController

Now in second step, i have to create the FileController controller with index() and store(). I have to create the “files” folder in public folder. I will be store all files on that folder. just need to create new controller and put the bellow code on it:

app/Http/Controllers/FileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class FileController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('fileUpload');
    }
   
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    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.']);
    }
}
Step 4: Create Blade File

Now in this Last step, i have to create the fileUpload.blade.php file and then i will write code for jquery and then show you with progress bar. So i have to simply add the bellow code on following path:

resources/views/fileUpload.blade.php

<!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 - CodingsPoint.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 File Upload with Ajax Progress Bar Example - CodingsPoint.com</h2>
        </div>  
        <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-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) {
                        console.log('File has uploaded');
                    }
                });
            });
        });
    </script>
</body>
</html>

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like