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.
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
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
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'
];
}
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.']);
}
}
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']);
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 8 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">jQuery Ajax File uploading with Progress Bar Example - Laravelcode</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>
now run your laravel application using the following artisan command.
php artisan serve
then simply run the following URL in your browser and test your file uploading with progress bar functionality.
http://127.0.0.1:8000/file-upload
i hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel 8 send Bulk Mail in Background using Queue
While working on functionality which tak...Realtime Event Broadcasting using Socket.io in Laravel7.x with Example
In the today’s technogy age genuin...Laravel 8 Default Password Validation Rules
Password is the most important data in a...How to make the first letter of a string uppercase in JavaScript
Use the toUpperCase() method In JavaS...How to Send POST Request Without Waiting for Response?
In this article, I will share with you h...