Progress Bar Using AJAX/PHP

Author - Webner
23.10.2019
|
0 Comments
|

Progress Bar For Large Uploads Using AJAX/PHP

Problem:
When large files are being uploaded, a server at the back takes time to upload the same file. Users have to wait irrespective of knowing, whether the file is even being uploaded or not and how much of the file has been uploaded.
Solution:
We can achieve the same by using the progress method of AJAX, to make the user experience, much more convenient and user-friendly. Below is the code example for the same along with the explanatory comments:

Firstly, we need a file upload parsing snippet, which will handle the request from AJAX at the server end. Save the uploaded file parser code as fileParser.php at the server end, to which our AJAX will POST the form data including the file that has to be uploaded.

fileParser.php –

<?php
    $fileName = $_FILES["selected_file"]["name"]; // Getting selected file name
    $fileTempLoc = $_FILES["selected_file"]["tmp_name"]; // Moving file to PHP Temp folder
    $fileType = $_FILES["selected_file"]["type"]; // Getting the type of the selected file
    $fileSize = $_FILES["selected_file"]["size"]; // Getting the file size in Bytes
    $fileErrorMsg = $_FILES["selected_file"]["error"]; // This returns a Boolean(0 for False;1 for True)
    if (!$fileTempLoc) { // Check whether file has been selected or not
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    }
    if(move_uploaded_file($fileTempLoc, "test_uploads/$fileName")){
        echo "$fileName upload is complete";
    } else {
        echo "move_uploaded_file function failed";
}
?>

After our function has been successfully created, here is a simple HTML form with Bootstrap 4 components. Include the Bootstrap and jQuery CDNs in the following snippet at the top:

form.html –

 
<h2>File Upload Progress Bar</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="selected_file" id="selected_file" onchange="uploadFile()">
<progress id="progressBar" class="progress-bar progress-bar-striped bg-success" value="0" max="100" style="width:300px;"> <h3 id="status"> <p id="loaded_n_total">

Here is the script, that we need to add inside the HTML code. Below is the JS snippet along with the explanatory comments regarding the main logic parts:

 
function _(element) {
    return document.getElementById(element); //Getting the reference of the File element
}
 
function uploadFile() {
    var file = _("selected_file").files[0]; //Getting the first file selected from the file element array
    var formdata = new FormData();
    formdata.append("selected_file", file);
    var ajax = new XMLHttpRequest(); // Creating XMLHttp object to make AJAX call. 
    ajax.upload.addEventListener("progress", progressHandler, false); // Function for progress event of AJAX
    ajax.addEventListener("load", completeHandler, false); // Function for load event of AJAX
    ajax.addEventListener("error", errorHandler, false); // Function for error event of AJAX
    ajax.addEventListener("abort", abortHandler, false); // Function for abort event of AJAX
    ajax.open("POST", "fileParser.php"); 
    ajax.send(formdata);
}
 
function progressHandler(event) {
    _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
    var percent = (event.loaded / event.total) * 100; // Calculating Total progress
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
 
function completeHandler(event) {
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0; // This will bring progress bar back to 0 after successful upload
}
 
function errorHandler(event) {
    _("status").innerHTML = "Upload Failed";
}
 
function abortHandler(event) {
    _("status").innerHTML = "Upload Aborted";
}
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *