Laravel 9 Ajax File Upload With Progress Bar

Websolutionstuff | Nov-15-2022 | Categories : Laravel PHP jQuery

In this article, we will see the laravel 9 ajax file upload with a progress bar. we will learn how to file upload using ajax jquery in laravel 9. You can upload files without page refresh with a progress bar. when uploading any document, image, or file on the server it may take some time to upload but for better understanding and display we will use the progress bar with file upload in laravel 9.

So, let's see jquery ajax file upload with a progress bar and file upload using ajax in laravel 9.

AJAX File Upload With Progress Bar In Laravel 9

Step 1: Install Laravel 9

Step 2: Create Routes

Step 3: Create FileUploadController

Step 4: Create Blade File

Step 5: Run Laravel 9 Application

 

Step 1: Install Laravel 9

In this step, we will install the laravel 9 application using the following command.

composer create-project laravel/laravel ajax-file-upload

 

 

Step 2: Create Routes

Now, we will create two routes in the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FileUploadController;
  
/*
|--------------------------------------------------------------------------
| 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(FileUploadController::class)->group(function(){
    Route::get('file-upload', 'index');
    Route::post('file-upload', 'store')->name('file.upload');

 

Step 3: Create FileUploadController

In this step, we will create FileUploadController and creates a "documents" folder in the public folder. in this folder, we will store all the files.

app/Http/Controllers/FileUploadController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class FileUploadController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('file_upload');
    }
   
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
   
        $file_name = time().'.'.request()->file->getClientOriginalExtension();
   
        request()->file->move(public_path('documents'), $file_name);
   
        return response()->json(['success'=>'You have successfully upload file.']);
    }
}

 

 

Step 4: Create Blade File

In this step, we will create the file_upload.blade.php file. So, create a blade file and add the code in this file.

resources/views/file_upload.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 9 Ajax File Upload With Progress Bar - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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">Ajax File Upload with Progress Bar in Laravel 9 - Websolutionstuff</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>

 

Step 5: Run Laravel 9 Application

 Now, run the laravel 9 jquery ajax file upload with the progress bar application.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Validate International Phone Number Using jQuery
How To Validate International...

In this article, we will see how to validate international phone numbers using jquery. Here, we will learn about mo...

Read More

May-12-2023

Vue Js Get Array Of Length Or Object Length
Vue Js Get Array Of Length Or...

In this tutorial, we will see you example of vue js get an array of length or object length. we will learn about vu...

Read More

Jan-07-2022

How To Get Hourly Data In MySQL
How To Get Hourly Data In MySQ...

In this tutorial, we will see how to get hourly data in mysql. Many times we need to get hourly data or we are required...

Read More

Feb-04-2022

Laravel 8 One To One Relationship Example
Laravel 8 One To One Relations...

In this example we will see laravel 8 one to one relationship example also you can use one to one relationship in l...

Read More

Nov-01-2021