The most often utilised aspect of the dynamic web application is the file upload option. PHP may easily be used to build file upload capabilities. When you use PHP to upload a file, the page is usually updated. jQuery and Ajax can be used to upload files/images without requiring a page refresh, making this file upload more user-friendly.
The web page remains in the loading state while the file is being uploaded to the server. The user has a tough time tracking the upload progress. The Progress Bar can help you solve this problem by displaying the upload progress in a human-readable format. A progress bar is a graphical element that shows how an operation is progressing. In most cases, a progress bar is used to display percentage progress for upload, download, or installation. In this article, we’ll show you how to use jQuery and Ajax to upload a file and create a progress bar in PHP.
The following functionality will be implemented in the sample ajax progress bar with percentage script.
To select a file, use an HTML form.
Using jquery, show a progress bar while the upload is in progress.
Using Ajax, add a percentage of the upload completion to the progress bar in real time.
PHP is used to upload a file to the server.
Examine the file structure before beginning to integrate file upload with progress metre.
php_file_upload_with_progress_bar_jquery/ ├── index.html ├── upload.php ├── uploads/ ├── js/ │ └── jquery.min.js ├── css/ │ └── style.css └── images/
Form for uploading files with a progress bar
The file selection and live upload progress display procedures are handled by the index.html file.
1. Create an HTML form that includes a file input box and a submit button.
The enctype=”multipart/form-data” attributes must be included in the form> tag.
type=”file” must be included in the input> tag.
<!-- 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>
To display the progress bar, create an HTML element.
<!-- Progress bar -->
<div class="progress">
<div class="progress-bar"></div>
</div>
Create an HTML element to show the status of the file upload.
<!-- Display upload status -->
<div id="uploadStatus"></div>
Ajax File Upload with Progress Bar: To upload a file with a progress bar, you’ll need to include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>/* Your code... */
Without reloading the page via Ajax, the following jQuery code delivers the selected file data to the server-side script.
jQuery and Ajax are used to send the selected file data to the server-side script (upload.php) when the form is submitted.
The $.ajax() method’s xhr argument is used to track the upload progress.
The view from the window.
A new XMLHttpRequest object is created by calling the XMLHttpRequest() function.
The progress event of the XMLHttpRequest upload property tells how far the request has progressed.
The percentage of upload progress is displayed on the progress bar.
The submitted file data is retrieved using the FormData object.
The upload status is displayed on the webpage based on the response.
The file type is validated based on the authorised kinds when a change event occurs.
The File API is used to determine the file’s type.
The user can only upload image (.jpeg/.jpg/.png/.gif) or PDF (.pdf) or MS Word (.doc/.docx) files if the MIME type of the selected file is validated.
The includes() method checks whether the selected file type is present in the allowedTypes array.
<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>
PHP is used to upload a file to a server.
The Ajax request calls the upload.php file, which uses PHP to perform the file upload procedure.
Using the PHP $_FILES method, you can get file information from uploaded data.
The move uploaded file() method in PHP is used to upload the file to the server.
Return to the Ajax success function after rendering the file upload status.
<?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;
?>
Note:
The progress bar is a convenient way to see the upload completion status in real time. You can use jQuery to add a percentage progress bar to a file upload and display it while the file is being uploaded to the server. In PHP, you may add a progress bar to any sort of file upload (image, pdf, doc, docx, audio, video, and so on). Our example code demonstrates how to create a % progress indicator for upload, download, and installation processes.