Image / file upload should always have a progress bar. It is a feature that most of the developers ignore. It should be seen as part of the functionality. The users cannot sit in the dark and keep guessing about the background progress.
When the user requests the server to perform some operation, it is good to show them about the progress. It is a good UI/UX behavior.
The progress bar is one of the best ways to show the status of the in-progress operation. We have already seen how to show a dynamic progress bar to display file upload progress. In this example, let us learn to create an animating progress bar using jQuery while uploading an image via AJAX.
A file input option is used to choose the image and the file binaries are posted to the PHP via AJAX. After sending the file upload request to the PHP, the AJAX script initializes jQuery animation to show the file upload progress bar.
The progress bar will highlight the progressing percentage with jQuery animation. The jQuery Form plugin is used in this example code to handle the AJAX image upload with progressive status.
The landing page will show a HTML form with the file input. Users will choose the file and post the file data by submitting the form via AJAX. The jQuery and jQuery Form library is included at the beginning of the script.
A minimal jQuery validation script is added to check if the image file had been chosen before submitting the form.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
type="text/javascript"></script>
<script type="text/javascript" src="jquery.form.min.js"></script>
</head>
<body>
<h1>jQuery Ajax Image Upload with Animating Progress Bar</h1>
<div class="form-container">
<form action="uploadFile.php" id="uploadForm" name="frmupload"
method="post" enctype="multipart/form-data">
<input type="file" id="uploadImage" name="uploadImage" /> <input
id="submitButton" type="submit" name='btnSubmit'
value="Submit Image" />
</form>
<div class='progress' id="progressDivId">
<div class='progress-bar' id='progressBar'></div>
<div class='percent' id='percent'>0%</div>
</div>
<div style="height: 10px;"></div>
<div id='outputImage'></div>
</div>
</body>
</html>
The jQuery form library is used to submit the form via AJAX with an animated progress bar. The ajaxForm() function is used to submit the image file binaries to the PHP. The progress of the image upload is shown with a progress bar in the uploadProgress callback function.
Also, the jQuery animate() method is called to create the progressing effect on the progress bar element.
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton').click(function () {
$('#uploadForm').ajaxForm({
target: '#outputImage',
url: 'uploadFile.php',
beforeSubmit: function () {
$("#outputImage").hide();
if($("#uploadImage").val() == "") {
$("#outputImage").show();
$("#outputImage").html("<div class='error'>Choose a file to upload.</div>");
return false;
}
$("#progressDivId").css("display", "block");
var percentValue = '0%';
$('#progressBar').width(percentValue);
$('#percent').html(percentValue);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentValue = percentComplete + '%';
$("#progressBar").animate({
width: '' + percentValue + ''
}, {
duration: 5000,
easing: "linear",
step: function (x) {
percentText = Math.round(x * 100 / percentComplete);
$("#percent").text(percentText + "%");
if(percentText == "100") {
$("#outputImage").show();
}
}
});
},
error: function (response, status, e) {
alert('Oops something went.');
},
complete: function (xhr) {
if (xhr.responseText && xhr.responseText != "error")
{
$("#outputImage").html(xhr.responseText);
}
else{
$("#outputImage").show();
$("#outputImage").html("<div class='error'>Problem in uploading file.</div>");
$("#progressBar").stop();
}
}
});
});
});
</script>
This is the usual PHP code used to upload the image file to a specified target folder. The file data are stored in the $_FILES superglobal. PHP move_uploaded_file() function is used to copy the submitted file to the target uploads folder.
<?php
if (isset($_POST['btnSubmit'])) {
$uploadfile = $_FILES["uploadImage"]["tmp_name"];
$folderPath = "uploads/";
if (! is_writable($folderPath) || ! is_dir($folderPath)) {
echo "error";
exit();
}
if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $folderPath . $_FILES["uploadImage"]["name"])) {
echo '<img src="' . $folderPath . "" . $_FILES["uploadImage"]["name"] . '">';
exit();
}
}
?>
This was really useful to me. Thank you!
Welcome Onoja.
Works great, but I am wondering is there a way to implement this on multiple=”multiple” file input?
Hi Joakim,
Need to enhance the script a bit. Will try to do it soon. Thank you.
where youtube tutorial?
Hi Bugine,
I am working on launching a YouTube channel soon. Thank you.
Vincy please share, how to compressed image upload to directory and server……thank you
Check this https://phppot.com/php/php-compress-image/ and https://phppot.com/php/create-zip-file-of-multiple-uploaded-files-using-php/
This is a nice script
Thank you Daniel.
thank you
Welcome Tabrez.
Thanks for your work.
i really appreciate it.
thanks again.
keep smiling dear
Welcome Shivam.
you are great vincy, thank’s a lot
Welcome Houcine.
@Vincy This is a great job, well done.
But there is an error within the upload.
I tested it with a large file of over 10mb but the upload was done while the progress bar was still around 75%.
I hope that you can give it a try and hopefully correct it.
I even had to remove the duration count of 5000, it still did not bring up accurate information.
Aside from that you did a great job.
4 stars out of 5
Hi Joshua,
Thank you for the comment. I planned and tested it with smaller files. Sure, I have taken your comment and will work on it. Thank you.
It is Beautiful as well as Useful :)
Thank you Mushtaque.
Thanks
Welcome Atul.
Helped me lots!! Was just looking for this
Thank you Phino.