How to show progress bar on ajax multiple file upload

Jquery

Posted on 26 Apr 18 by Vickey
  386



By using ajax we can send and receive response from server without refresh the webpage page. We can submit form and can upload files on server by using ajax call. But if we will upload multiple file at once then total post size will increase that will impact performance and file uploading process may be crash or kill. So the correct way is that we will send file on server one by one. In this blog we will upload multiple file one by one with progress bar. We will drag and drop multiple file and add all files in a queue and send these on server one by one with showing a progress bar. we can do this by adding a parameter 'async: false in ajax call but by doing this we can not show progress bar because synchronous ajax call will freeze ui so the progress bar will not work.so we have a another method to do this. let's start.

First of all create a html file 'index.html' and add the below code

<html>
<head>
	<script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
	<body style="background: #d8d2d2;">
		<form>
			<div id="dragandrophandler" style="border: 2px #478FCA dashed;width: 35%;padding: 5%;margin:0 auto;text-align: center; margin-top: 100px;">
				<i class="fas fa-cloud-upload-alt" style="font-size: 8em;color:#478FCA;"></i>
			</div>
			<div style="border:1px solid #478FCA;margin:20px auto;width: 45%;display:none;" id="file_upload_progress_bar">
  					
			</div>
		</form>
	</body>
</html>
<script>
    var obj = $("#dragandrophandler");
    obj.on('dragenter', function (e)
    {
        e.stopPropagation();
        e.preventDefault();
    });
    obj.on('dragover', function (e)
    {
        e.stopPropagation();
        e.preventDefault();
    });
    var filesForUpload = [];
    obj.on('drop', function (e)
    {
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        for (var current_file = 0; current_file < files.length; current_file++)
        {
            var fd = new FormData($('#hiddenElements')[0]);
            fd.append('filesToBeUpload', files[current_file]);
            filesForUpload.push(fd);
            var total_files = parseInt(filesForUpload.length);
        }
        var uploadingStartPercentage = parseInt(100 / total_files);
        uploadingPercentage = uploadingStartPercentage;
        sendFileToServer(filesForUpload, total_files, 1, uploadingStartPercentage, uploadingPercentage);
        
    });
    function sendFileToServer(filesForUpload,total_files, currentFile, uploadingStartPercentage, uploadingPercentage)
    {
        var data = filesForUpload[0];
        filesForUpload.splice(0, 1);
        $("#file_upload_progress_bar").show();
        $.ajax({
            url: 'upload.php',
            type: "POST",
            data: data, 
            contentType: false, 
            cache: false,
            processData: false,
            success: function (responce){},
            error: function (request, status, error) { alert("File upload failed") },
            complete: function () {
                console.log(uploadingPercentage);
                $("#file_upload_progress_bar").html('<div  style="height:24px;width:'+uploadingPercentage+'%;background: #478FCA;color:#fff;padding-top: 6px;"></div>');
                if (filesForUpload.length > 0) {
                    sendFileToServer(filesForUpload,total_files,currentFile+1,uploadingStartPercentage,uploadingStartPercentage+uploadingPercentage);
                } 
                else {
                    $("#file_upload_progress_bar").html('<div  style="height:24px;width:100%;background: #478FCA;color:#fff;padding-top: 6px;"></div>');
                    //window.location = "/";
                }
            }
        });
    }
</script>

Now create a php file where we will upload file by using php

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["filesToBeUpload"]["name"]);
if (move_uploaded_file($_FILES["filesToBeUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["filesToBeUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

Thanks for reading this blog

You can download source code here


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com