Laravel 9 - jQuery Ajax File Upload with Progress Bar Tutorial
In this article, i will share with you how to upload file with progress bar in laravel with simple example. file uploading feature is very common things in laravel application. but here i will not show you simple file uploading but here we will see file uploading usisng jquery ajax with progress bar.
File uploading using ajax it's main advantage browser window not need to refresh. when you need file upload with not page refresh then ajax was best option for make any king of functionality in your laravel application.
in this tutorial file upload with progress bar we covert the following steps.
- Step 1: Create Laravel Application
- Step 2: Connect to Database
- Step 3: Configure Model and Migration
- Step 4: Create Controller
- Step 5: Create Routes
- Step 6: Create view
- Step 7: Start Laravel App
Step - 1: Create Laravel Application
In the first step we will create the fresh laravel application by running the following command in your terminal.
composer create-project --prefer-dist laravel/laravel file-upload-demo
Step - 2: Connect to Database
After create the fresh laravel application then the you need to configure your database setting in your .env
file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Step - 3 : Configure Model and Migration
in this step we will create laravel migration for the store fil upload data into database.
php artisan make:migration create_file_uploads_tbl
running the above command in your terminal then open your created migration file and change into it.
database/migrations/create_file_uploads_tbl.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFileUploadsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('file_uploads', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('file_uploads');
}
}
then run your migration by php artisan migrate
command.
after, create migration then now create the file upload model in your laravel application by running the following command.
php artisan make:model FileUpload
app/Models/FileUpload.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class FileUpload extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Step - 4: Create Controller
Now, create the ProgressBarController
by running the following command.
php artisan make:controller ProgressBarController
app/Http/Controllers/ProgressBarController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FileUpload;
class ProgressBarController extends Controller
{
public function index()
{
return view('fileupload');
}
public function uploadToServer(Request $request)
{
$request->validate([
'file' => 'required',
]);
$name = time().'.'.request()->file->getClientOriginalExtension();
$request->file->move(public_path('uploads'), $name);
$file = new FileUpload;
$file->name = $name;
$file->save();
return response()->json(['success'=>'Successfully uploaded.']);
}
}
Step - 5: Create Routes
create the following route in your routes/web.php
file.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProgressBarController;
/*
|--------------------------------------------------------------------------
| 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('/file-upload', [ProgressBarController::class, 'index']);
Route::post('/upload-doc-file', [ProgressBarController::class, 'uploadToServer']);
Step - 6: Create view
now, create the fileupload.blade.php
file into resources/views
folder and write the following code into it.
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 9 Bootstrap 5 Progress Bar Example</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: 500px">
<div class="alert alert-warning mb-4 text-center">
<h2 class="display-6">Laravel Dynamic Ajax Progress Bar Example</h2>
</div>
<form id="fileUploadForm" method="POST" action="{{ url('/upload-doc-file') }}" enctype="multipart/form-data">
@csrf
<div class="form-group mb-3">
<input name="file" type="file" class="form-control">
</div>
<div class="d-grid mb-3">
<input type="submit" value="Submit" class="btn btn-primary">
</div>
<div class="form-group">
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
</div>
</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 - 7: Start Laravel App
now run your laravel application using the following artisan command.
php artisan serve
http://127.0.0.1:8000/file-upload
i hope you like this article.
Copyright 2024 ErrorGram