Menu Close

JavaScript Multiple File Upload Progress Bar Using Ajax With PHP

codeamend

In this tutorial, we will see how to upload multiple file with progress bar using vanilla JavaScript and Ajax with PHP. Progress bar is very useful to check the file uploading status when we upload the files onto the server. Progress bar displays the live uploading process in the format of percentage of the file to the server. The progress bar displays the percentage in the form of a graphical element when we upload, download and install files or any softwares. 

Here, we will use pure vanilla JavaScript and Ajax to select multiple files to the server at client side and PHP for the server side.

Follow the steps below,

Create index.php file

Here, we have used bootstrap 5 stylesheet  for styling. 

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <title>Upload Multiple Files with Progress Bar using PHP and JavaScript - Codeamend</title>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-7 mx-auto">
                    <h1 class="h2 mt-3 mb-3 text-center">Upload Multiple Files with Progress Bar</h1>
                    <div class="card text-center bg-light text-dark mb-4">
                        <div class="card-header">
                            <h3>Select File</h3>
                        </div>
                        <div class="card-body">
                            <input type="file" id="select_file" multiple />
                        </div>
                    </div>
                    <div class="progress" id="progress_bar" style="display:none; ">
                        <div class="progress-bar" id="progress_bar_process" role="progressbar" style="width:0%">0%</div>
                    </div>
                    <div id="uploaded_image" class="row mt-5"></div>
                </div>
            </div>
        </div>
    </body>
</html>

<script>
function _(element){
    return document.getElementById(element);
}
_('select_file').onchange = function(event){

    var form_data = new FormData();

    var image_number = 1;

    var error = '';

    for(var count = 0; count < _('select_file').files.length; count++)  {
        if(!['image/jpeg', 'image/png', 'video/mp4'].includes(_('select_file').files[count].type)){
            error += '<div class="alert alert-danger"><b>'+image_number+'</b> Selected File must be .jpg or .png Only.</div>';
        } else {
            form_data.append("images[]", _('select_file').files[count]);
        }
        image_number++;
    }

    if(error != ''){
        _('uploaded_image').innerHTML = error;
        _('select_file').value = '';
    } else {
        _('progress_bar').style.display = 'block';
        var ajax_request = new XMLHttpRequest();
        ajax_request.open("POST", "upload.php");
        ajax_request.upload.addEventListener('progress', function(event){
            var percent_completed = Math.round((event.loaded / event.total) * 100);
            _('progress_bar_process').style.width = percent_completed + '%';
            _('progress_bar_process').innerHTML = percent_completed + '% completed';
        });
        ajax_request.addEventListener('load', function(event){
            _('uploaded_image').innerHTML = '<div class="alert alert-success">Files Uploaded Successfully</div>';
            _('select_file').value = '';
        });
        ajax_request.send(form_data);
    }
};
</script> 

Create upload.php file

<?php
//upload.php
if(isset($_FILES['images'])){
	for($count = 0; $count < count($_FILES['images']['name']); $count++){
		$extension = pathinfo($_FILES['images']['name'][$count], PATHINFO_EXTENSION);
        $new_name = uniqid() . '.' . $extension;
        move_uploaded_file($_FILES['images']['tmp_name'][$count], 'uploads/' . $new_name);
    }
    echo 'success';
}
?> 

Share

Posted in Ajax, Codeamend, JavaScript, PHP

You can also read...

Leave a Reply

Your email address will not be published.