article

Thursday, May 25, 2023

Laravel 10 File Upload Progress Bar Using Ajax

Laravel 10 File Upload Progress Bar Using Ajax

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

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

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model File -m

A new file named File.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/File.php

//app/Models/File.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;

    protected $fillable = [
        'title'
    ];
}
database\migrations\create_files_table.php
//database\migrations\create_files_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('files');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.

check database table
br/> Create Controller
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller UploadFileController

app\Http\Controllers\UploadFileController.php
//app\Http\Controllers\UploadFileController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;

class UploadFileController extends Controller
{
    public function index()
    {
        return view('fileupload');
    }
 
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
 
       $title = time().'.'.request()->file->getClientOriginalExtension();
  
       $request->file->move(public_path('upload'), $title);
 
       $storeFile = new File;
       $storeFile->title = $title;
       $storeFile->save();
  
        return response()->json(['success'=>'File Uploaded Successfully']);
    }
}
Create View File
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

jQuery Form
https://github.com/jquery-form/form

resources/views/fileupload.blade.php
//resources/views/fileupload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 File Upload Progress Bar Using Ajax</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<style>
    .progress { position:relative; width:100%; }
    .bar { background-color: #2dab27; width:0%; height:20px; }
    .percent { position:absolute; display:inline-block; left:50%; color: #040608;}
</style>
</head>
<body>
<div class="container mt-5">
    <div class="card">
    <div class="card-header text-center">
        <h2>Laravel 10 File Upload Progress Bar Using Ajax</h2>
    </div>
    <div class="card-body">
        <form method="POST" action="{{ url('store') }}" 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>
    </div>
</div>
<script type="text/javascript">
    var SITEURL = "{{URL('/')}}";
    $(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 = SITEURL +"/"+"ajax-file-upload-progress-bar";
                }
            });
        }); 
    });
</script>
</body>
</html>
routes/web.php
//routes/web.php
<?php

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

Route::get('/', function () {
    return view('welcome');
});

Route::get('ajax-file-upload-progress-bar', [UploadFileController::class, 'index']);
Route::post('store', [UploadFileController::class, 'store']);
Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve Starting Laravel development server: http://127.0.0.1:8000/ajax-file-upload-progress-bar

Related Post