Tuesday, 12 July 2022

File Upload with Progress Bar using Vanilla JavaScript in Laravel 9


In this Laravel 9 Tutorial, You will learn Laravel 9 Upload Image with Progress Bar using Vanilla JavaScript. Under this post we will show you simple example of Laravel 9 File Upload with Bootstrap 5 Progress Bar using Vanilla JavaScript. So in this post you will learn Laravel 9 Ajax File Upload with progress bar. So with the help of this tutorial you will learn how to display Laravel 9 File Upload process on progress bar.

If you have use this tutorial Fil Upload with Progress bar in Laravel 9, Laravel 8, Laravel 7 & Laravel 6 framework.

We have do simple file uploading, if our file size is small, so we can do file upload in a very normal and file has been easily uploaded. But when we have large amount of file size then it will takes time to upload large file on a server. So if file upload takes more times for upload to the server, then we can not reduce that file upload time, so for solve this problem, Here we can display file upload process on the progress bar in percentage value. So after display file upload process in percentage on progress bar, then user can understand how much time is left to upload file to server.

So In this Laravel 9 Framework, we will create one web page with select file tag for select file from local computer, so when we have select file from local computer then by using Vanilla JavaScript, it will trigger ajax request send file to server and then after display file upload process on progress bar in percentage. So when File has been uploaded on the server using JavaScript in Laravel 9 framework, then it will display success message with uploaded image on the web page. For create File Upload with Progress bar in Laravel 9 framework using JavaScript, then you have to follow below steps.


File Upload with Progress Bar using Vanilla JavaScript in Laravel 9


Step 1 : Install Laravel 9 Framework


First We have to download and install Laravel 9 framework in our computer. But before downloading Laravel 9 framework, you have to install PHP 8 version your local computer. So for download Laravel 9 framework, you have goes to command prompt and goes into directory where you have exectute PHP script and then after you have to run following command, which will create javascript_file_upload directory and under that directory it will download and install Laravel 9 framework.


composer create-project laravel/laravel javascript_file_upload





Step 2 : Create File Controller in Laravel 9


In the second steps, we have to create FileController class. For this, we have goes to command prompt and run following command, which will create FileController.php file in app/Http/Controllers directory.


php artisan make:controller FileController


Once Controller file has been created, then after we have to create index() and upload() method. And you have to create images directory under public directory and we will upload files under this images folder. Below you can find FileController.php file code

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    function index()
    {
        return view('javascript_file_upload');
    }

    function upload(Request $request)
    {
        $file_name = time() . '.' . request()->sample_image->getClientOriginalExtension();

        request()->sample_image->move(public_path('images'), $file_name);

        $image_path = asset('images/'. $file_name);

        return response()->json(['image_path'=>$image_path]);
    }
}



Step 3 : Create Blade View File


Under this step, we have to create javascript_file_upload.blade.php blade view file. Under this file, we have use Bootstrap 5 library for display file upload process on progress bar. In this file, we have to create one file tag for select file from local computer and then after we have to write Vanilla JavaScript code, for display file upload process on progress bar. You have to add following code under this View Blade file for Upload File with Progress bar using JavaScript.

resources/views/javascript_file_upload.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 JavaScript File Upload with Progress Bar</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 9 JavaScript File Upload with Progress Bar</h2>
        </div>  
        @csrf
        <div class="card">
            <div class="card-header">Select File</div>
            <div class="card-body">
                <table class="table">
                    <tr>
                        <td width="50%" align="right"><b>Select File</b></td>
                        <td width="50%">
                            <input type="file" id="select_file" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <br />
        <div class="progress" id="progress_bar" style="display:none;height:50px; line-height: 50px;">

            <div class="progress-bar" id="progress_bar_process" role="progressbar" style="width:0%;">0%</div>

        </div>

        <div id="uploaded_image" class="row mt-5"></div>
    </div>
    
</body>
</html>

<script>

var file_element = document.getElementById('select_file');

var progress_bar = document.getElementById('progress_bar');

var progress_bar_process = document.getElementById('progress_bar_process');

var uploaded_image = document.getElementById('uploaded_image');

file_element.onchange = function(){

    if(!['image/jpeg', 'image/png'].includes(file_element.files[0].type))
    {
        uploaded_image.innerHTML = '<div class="alert alert-danger">Selected File must be .jpg or .png Only</div>';

        file_element.value = '';
    }
    else
    {
        var form_data = new FormData();

        form_data.append('sample_image', file_element.files[0]);

        form_data.append('_token', document.getElementsByName('_token')[0].value);

        progress_bar.style.display = 'block';

        var ajax_request = new XMLHttpRequest();

        ajax_request.open("POST", "{{ route('upload_file.upload') }}");

        ajax_request.upload.addEventListener('progress', function(event){

            var percent_completed = Math.round((event.loaded / event.total) * 100);

            progress_bar_process.style.width = percent_completed + '%';

            progress_bar_process.innerHTML = percent_completed + '% completed';

        });

        ajax_request.addEventListener('load', function(event){

            var file_data = JSON.parse(event.target.response);

            uploaded_image.innerHTML = '<div class="alert alert-success">Files Uploaded Successfully</div><img src="'+file_data.image_path+'" class="img-fluid img-thumbnail" />';

            file_element.value = '';

        });

        ajax_request.send(form_data);


    }

};

</script>


Step 4 : Set Routes of Controller Method


Once our code is ready, now in Laravel 9 framework, we have to set route of the FileController.php class method. In this step, we have to set get route for display select file web page in the browser and second one is post route for upload file under public directory images folder. So, we have to open routes/web.php file and under this file, we have to write following code for create routes in Laravel 9 framework.

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('upload_file', 'index');

    Route::post('upload_file/upload', 'upload')->name('upload_file.upload');
    
});


Step 5 : Run Laravel 9 Application


If we have follow all above steps now we have to check output in the browser, so we have goes to command prompt and run following command which will run Laravel 9 application.


php artisan serve


Now we have go to browser and type following url in the browser for view Laravel 9 File Upload with Progress bar using JavaScript output.


http://localhost:8000/upload_file



0 comments:

Post a Comment