The most commonly utilised capability for the dynamic web app is the file upload option. PHP may be used to simply develop file upload capabilities. When you upload a file with PHP, the website is usually updated. jQuery and Ajax may be used to transfer files/images without requiring a page refresh to render this file upload more user-friendly.
The web page remains in the loading stage while the file is being uploaded to the server. The user has a tough time tracking the upload process. The Progress Bar can help you address this problem by displaying the transfer status in a human-readable way. A toolbar is a visual component that depicts how an operation is progressing. In general, a progress bar is used to display progress in form of percentage for uploading, downloading, or installation. In this article, we'll teach you how to use jQuery and Ajax to upload a file and create a progress bar.
The index.html file is in charge of file selection and displaying the live upload process.
1. Design an HTML form that includes a file html form and a submit button.
- The enctype="multipart/form-data" attributes must be included in the form> tag.
- The type="file" attribute 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>
2. Create an HTML element that will display the progress bar.
<!-- Progress bar -->
<div class="progress">
<div class="progress-bar"></div>
</div>
3. Create an HTML element that will show the file upload status.
<!-- Display upload status -->
<div id="uploadStatus"></div>
Ajax File Upload with Progress Bar:
Because jQuery and Ajax are needed to upload files with a progress bar, the jQuery library must be included first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The jQuery code below delivers the data from the specified file to the server-side script without refreshing the page using Ajax.
- Using jQuery and Ajax, the selected file data is delivered to the server-side script (upload.php) upon form submission.
- The $.ajax() method's xhr argument is used to track the upload progress.
- The window.XMLHttpRequest() function is used to generate a new XMLHttpRequest object.
- The progress event of the XMLHttpRequest upload property tells how far the request has progressed.
- The percentage of upload progress is tied to the progress bar.
- The FormData object is used to obtain the data from the submitted file.
- The upload status is shown on the webpage based on the answer.
- The type of file is verified based on the authorised kinds at the change event.
- The File API is used to determine the type of the currently chosen file.
- The MIME type of the selected file is validated, and the user is restricted to uploading only image (.jpeg/.jpg/.png/.gif) or PDF (.pdf) or MS Word (.doc/.docx) files.
- The includes() function checks to see if the given file type is 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>
The Ajax request calls the upload.php file, which handles the file upload procedure with PHP.
- Using the PHP $_FILES method, you may retrieve file information from uploaded data.
- Using PHP's move uploaded file() method, 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; ?>
The taskbar icon is a simple approach to display the uploading progress status in real time. Users can use jQuery to attach a toolbar to an uploading files and display a % countdown timer as the file uploads to the server. In PHP, you may add a progress bar to any sort of uploading files (PDF, Docx, Video, image, doc, audio, etc.). Our example code demonstrates how to create a progress bar with a % for uploading, downloading, and installation processes.
© ThemesGiant Copyright @2015-2022 | All rights reserved.