The file upload feature is the most used functionality for the dynamic web application. The file upload functionality can be facilely implemented utilizing PHP. Generally, the page is refreshed when you upload file utilizing PHP. To make this file upload utilizer-cordial, jQuery and Ajax can be acclimated to upload files/images without page refresh.
While the file is uploading to the server, the web page stays on the loading state. It’s very arduous for the utilizer to track the upload progress. Progress Bar is very utilizable to surmount this issue by exhibiting the upload progress in a human-readable format. A progress bar is a graphical element that visualizes the progression of an operation. Generally, a progress bar is utilized to show progress representation in percentage format for upload, download, or installation. In this tutorial, we will show you how to upload file in PHP and make a progress bar utilizing jQuery and Ajax.
In the example ajax progress bar with percentage script, we will implement the following functionality.
Before getting started to integrate file upload with progress bar, take a look at the file structure.
php_file_upload_with_progress_bar_jquery/
├── index.html
├── upload.php
├── uploads/
├── js/
│ └── jquery.min.js
├── css/
│ └── style.css
└── images/
The index.html
file handles the file selection and live upload progress display operations.
File Upload Form:
1. Create an HTML form with a file input field and a submit button.
enctype="multipart/form-data"
attributes.type="file"
.<!-- File upload form -->
<form id="uploadForm" enctype="multipart/form-data">
<label>Choose File:</label>
<input type="file" name="file" id="fileInput">
<input type="submit" name="submit" value="UPLOAD"/>
</form>
2. Define an HTML element to display the progress bar.
<!-- Progress bar -->
<div class="progress">
<div class="progress-bar"></div>
</div>
3. Define an HTML element to display the file upload status.
<!-- Display upload status -->
<div id="uploadStatus"></div>
Ajax File Upload with Progress Bar:
The jQuery and Ajax is used to upload file with a progress bar, so include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The following jQuery code sends the selected file data to the server-side script without reloading the page via Ajax.
upload.php
) using jQuery and Ajax.
xhr
option of the $.ajax()
method is used to track the upload progress.window.XMLHttpRequest()
method creates a new XMLHttpRequest object.progress
event of XMLHttpRequest upload
property indicates the amount of progress made so far.includes()
method determines whether allowedTypes array contains the selected file type<script>
$(document).ready(function(){
// File upload via Ajax
$("#uploadForm").on('submit', function(e){
e.preventDefault();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = ((evt.loaded / evt.total) * 100);
$(".progress-bar").width(percentComplete + '%');
$(".progress-bar").html(percentComplete+'%');
}
}, false);
return xhr;
},
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$(".progress-bar").width('0%');
$('#uploadStatus').html('<img src="images/loading.gif"/>');
},
error:function(){
$('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
},
success: function(resp){
if(resp == 'ok'){
$('#uploadForm')[0].reset();
$('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
}else if(resp == 'err'){
$('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
}
}
});
});
// File type validation
$("#fileInput").change(function(){
var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
var file = this.files[0];
var fileType = file.type;
if(!allowedTypes.includes(fileType)){
alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).');
$("#fileInput").val('');
return false;
}
});
});
</script>
The upload.php
file is called by the Ajax request to handles the file upload process with PHP.
<?php
$upload = 'err';
if(!empty($_FILES['file'])){
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif');
$fileName = basename($_FILES['file']['name']);
$targetFilePath = $targetDir.$fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){
$upload = 'ok';
}
}
}
echo $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 Stripe card payment integration using paymentintent
Stripe payment provide payment intent&nb...How to Show Loading Spinner in jQuery
Use the ajaxStart() and ajaxStop() Metho...Python String Title method
Python String title() is an inbuilt stri...How To Install the Django Web Framework on Ubuntu
Django is one of the best and very popul...Laravel 8 Roles and Permissions Tutorial Part 2
In the previous tutorial article, we hav...