Laravel File Upload With Progress Bar Tutorial Example

In this example, I will explain to you how to do Laravel File Upload With Progress Bar Tutorial Example. When you were working with a big project, then the image or file may be large then you can’t reduce the size of the image or file, but you can display a progress bar to the user that how much time is remaining to upload a file. So, in this tutorial, we will create a file upload with a progress bar in laravel 5.6.

Laravel File Upload With Progress Bar Tutorial Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel 5.6 Project by the typing following command.

composer create-project --prefer-dist laravel/laravel laravelfileuploadprogressbar

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=fileuploadprogressbar
DB_USERNAME=root
DB_PASSWORD=

#3: Build Model and Migration File

php artisan make:model FileUpload -m

It will create the FileUpload.php file and also create a create_file_uploads_table.php  migration file.

public function up()
    {
        Schema::create('file_uploads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

#4: Create a View File

You can create a file in resources/views/fileupload.blade.php and put this following code in it.

<!-- fileupload.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Upload With Progress bar Tutorial Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <style>
        .progress { position:relative; width:100%; }
        .bar { background-color: #008000; width:0%; height:20px; }
         .percent { position:absolute; display:inline-block; left:50%; color: #7F98B2;}
   </style>
</head>
<body>
 
<div class="container">
        <h2>Laravel File Upload With Progress Bar Tutorial Example</h2>
            <form method="POST" action="{{ action('FileUploadController@fileStore') }}" enctype="multipart/form-data">
                @csrf
                <div class="form-group">
                    <input name="file" type="file" class="form-control"><br/>
                    <div class="progress">
                        <div class="bar"></div >
                        <div class="percent">0%</div >
                    </div>
                    <br>
                    <input type="submit"  value="Submit" class="btn btn-primary">
                </div>
            </form>    
</div>
</body>
</html>

#5: Create one controller

php artisan make:controller FileUploadController

It will build the controller file called FileUploadController.php.

//FileUploadController.php

public function fileUpload()
    {
        return view('fileupload');
    }

#6: Define Route

We register all route in a web.php file.

Route::get('fileupload', 'FileUploadController@fileUpload');
Route::post('fileupload', 'FileUploadController@fileStore');

Laravel File Upload With Progress Bar Example

#7: Add jQuery

Now, we can add jQuery code. Here we first include jquery.min.js and jquery.form.js. We use three function beforeSend(), uploadProgrees(), complete(). beforeSend() function define starting width and percentval in progressbar. uploadProgress() function define progess value of width and percentage in progressbar. complete() function works when complete the progress after alert display in the screen.

<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.2.2/jquery.form.js"></script>
 
<script type="text/javascript">
    $(function() {
         $(document).ready(function()
         {
            var bar = $('.bar');
            var percent = $('.percent');

      $('form').ajaxForm({
        beforeSend: function() {
            var percentVal = '0%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        complete: function(xhr) {
            alert('File Uploaded Successfully');
            window.location.href = "/fileupload";
        }
      });
   }); 
 });
</script>

Final code of imageupload.blade.php looks like that.

<!-- fileupload.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Upload With Progress bar Tutorial Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <style>
        .progress { position:relative; width:100%; }
        .bar { background-color: #008000; width:0%; height:20px; }
         .percent { position:absolute; display:inline-block; left:50%; color: #7F98B2;}
   </style>
</head>
<body>
 
<div class="container">
        <h2>Laravel File Upload With Progress Bar Tutorial Example</h2>
            <form method="POST" action="{{ action('FileUploadController@fileStore') }}" enctype="multipart/form-data">
                @csrf
                <div class="form-group">
                    <input name="file" type="file" class="form-control"><br/>
                    <div class="progress">
                        <div class="bar"></div >
                        <div class="percent">0%</div >
                    </div>
                    <br>
                    <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.2.2/jquery.form.js"></script>
 
<script type="text/javascript">
    $(function() {
         $(document).ready(function()
         {
            var bar = $('.bar');
            var percent = $('.percent');

      $('form').ajaxForm({
        beforeSend: function() {
            var percentVal = '0%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        complete: function(xhr) {
            alert('File Uploaded Successfully');
            window.location.href = "/fileupload";
        }
      });
   }); 
 });
</script>
</body>
</html>

#8: Store data to the database

Next, we are set to fill in fileStore() method with the logic to store data to the database. Also, we can shift the file to the images folder under a public directory. Put the following code in FileUploadController under fileStore() method.

use App\FileUpload;

public function fileStore(Request $request)
    {
        $request->validate([
            'file' => 'required',
		]);
       $fileName = time().'.'.request()->file->getClientOriginalExtension();
 
       $request->file->move(public_path('images'), $fileName);
       $fileupload = new FileUpload;
        $fileupload->filename=$fileName;
        $fileupload->save();
 
        return response()->json(['success'=>'File Uploaded Successfully']);
    }

Laravel File Upload With Progress Bar Tutorial

Final code of FileUploadController.blade.php looks like that.

//FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\FileUpload;

class FileUploadController extends Controller
{
    public function fileUpload()
    {
        return view('fileupload');
    }

    public function fileStore(Request $request)
    {
        $request->validate([
            'file' => 'required',
		]);
       $fileName = time().'.'.request()->file->getClientOriginalExtension();
 
       $request->file->move(public_path('images'), $fileName);
       $fileupload = new FileUpload;
        $fileupload->filename=$fileName;
        $fileupload->save();
 
        return response()->json(['success'=>'File Uploaded Successfully']);
    }
}

You can see the database in below screenshot.

Laravel 5.6 File Upload With Progress Bar Tutorial Example

At last, our Laravel File Upload With Progress Bar Tutorial Example is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.