Uploading files or images is a common task in web development. In this tutorial, we will learn how to upload files or images using PHP and jQuery with the progress bar. Uploading files with progress bar helps users to track the progress of the upload process and also gives them an idea of how much time is left for the upload to complete.
Prerequisites
Before we start, make sure you have the following:
- PHP installed on your system
- A web server like Apache or Nginx
- Basic knowledge of HTML, CSS, and JavaScript
- jQuery library installed on your system
Image/File Upload with Progressbar Using PHP & Jquery
Step 1: Create HTML Form
The first step is to create an HTML form that allows users to upload files. Create a new file called “index.php” and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Image/File Upload with Progressbar Using PHP & Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="js/upload.js"></script>
<style>
#progress {
width: 0%;
height: 30px;
background-color: #4CAF50;
color: white;
text-align: center;
line-height: 30px;
margin-top: 10px;
}
</style>
</head>
<body>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="submit" value="Upload File" name="submit">
</form>
<div id="progress"></div>
</body>
</html>
HTMLStep 2: Create PHP Upload Script
Now, we need to create a PHP script that will handle the file upload. Create a new file called “upload.php” and add the following code:
<?php
if(isset($_FILES["file"]["type"])){
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 1000000)//Approx. 1MB
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else{
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
} else{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "File uploaded successfully.";
}
}
} else{
echo "Invalid file format or size";
}
}
?>
PHPIn this code, we have checked whether the uploaded file is an image with a valid extension and size. If the file meets the criteria, it is moved to the “upload” folder. If the file already exists in the folder, an error message is displayed.
Step 3: Add jQuery Code
Now, we need to add jQuery code to handle the upload progress bar. Add the following code to the “index.php” file:
$(document).ready(function(){
var progress = $('#progress');
$('#uploadForm').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e){
if(e.lengthComputable){
var percent = Math.round((e.loaded / e.total) * 100);
progress.html(percent + '%');
progress.css('width', percent + '%');
}
});
return xhr;
},
success: function(response){
progress.html('Upload Complete!');
progress.css('width', '100%');
},
error: function(jqXHR, textStatus, errorThrown){
progress.html('Error: ' + textStatus);
console.log(errorThrown);
}
});
});
});
JavaScriptIn this code, we have added an event listener for the form submit event. When the form is submitted, we create a new FormData object to store the file data and use jQuery’s ajax() method to send the form data to the “upload.php” file.
We have also set the “async”, “cache”, “contentType”, and “processData” options to false to ensure that the file data is uploaded correctly.
The “xhr” option is used to get a reference to the XMLHttpRequest object and add an event listener for the “progress” event. This event is fired as the file is being uploaded and provides information about the upload progress. We use this information to update the progress bar in real-time.
Finally, we have added a “success” and “error” callback function to handle the server response. In the success function, we update the progress bar to indicate that the upload is complete. In the error function, we display an error message in case of any issues during the file upload.
If you have created all the files successfully time to test our code on browser.