简体   繁体   中英

How to make HTML Progress Bar Correctly

I am trying to make a Progress Bar for the uploaded progress in my application. So far I have this

<div class="col-sm-12">
    <span style="border-left:5px solid #555555; padding-left:.5em">Upload File</span>
    <div style="margin-top:1em; margin-left:.8em;">                               
        <input type="file" name="file" class="inputfile" id="group-agent-file" accept=".csv"/>
        <label for="file" id="span-file-upload" class="btn btn-danger">
            <span class="fa fa-upload" style="margin-right:.5em"></span>                                    
            <span id="span-file-name">Choose a file</span>
       </label>
   <div>
   <button type="button" id="btn-group-agent-upload" class="btn btn-primary" title="Upload">Upload</button>
</div>
<div class="progress">
     <div class="progress-bar progress-bar-green" role="progressbar" id="progress-bar-upload">
          <span></span>
     </div>                                
</div>    


and this is my javascript

var result = event.target.result;
var data = $.csv.toObjects(result);
var length = data.length;
var count = 0;
var percent;

$.each(data, function (key, val) {

    $.ajax({
        xhr: function(){
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function (evt) {
                console.log('progress', evt.loaded / evt.total * 100);
            };
        },
        type: "POST",
        url: "IROA_StoredProcedures.asmx/Insert_Bulk_Agent",
        data: JSON.stringify(val),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            count = count + 1;
            percent = count / length * 100;

            $("#progress-bar-upload").css("width", percent + "%");
            $("#progress-bar-upload span").text(percent + "% Complete");
            console.log("Finished " + count + " of " + length + " employees.");
        },
        error: function (XMLHttpRequest) {
            alert("error in Insert_Bulk_AgentInfo()");
            console.log(XMLHttpRequest);
        }

    });

});

it works fine but I think the html can't process enough that sometimes the width percentage is delayed. How can I do this? and what may be the drawbacks when I use setInterval .

To get upload progress in jQuery you need to attach Event-Listener to the progress event.

You can do something like this in jQuery

$.ajax({
xhr: function() {
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = (evt.loaded / evt.total);
            //Update the progress bar
        }
   });

   return xhr;
},
type: 'POST',
url: "/upload/path",
data: { YOUR UPLOAD DATA },
success: function (data) {
}
});

This would work the same for plain js

var xhr = new XMLHttpRequest();
xhr.open('POST', "/upload/path", true);
xhr.upload.addEventListener('progress', function (event) {
  if (evt.lengthComputable) {
    var percentComplete = (evt.loaded / evt.total);
    //Update the progress bar
  }
}
xhr.onload = function (response) {
  // handle success/error here
}
xhr.setRequestHeader(SET_HEADERS);
xhr.send(UPLOAD_DATA);

success function will be call when your ajax call gets completed. You should use xhr function instead of success.

xhr: function(){
                var xhr = $.ajaxSettings.xhr() ;
                xhr.upload.onprogress = function(evt){ 
                    console.log('progress', evt.loaded/evt.total*100); 
                    var percentageCompleted = evt.loaded/evt.total*100;
                    updateUploadPercentage(parseInt(percentageCompleted));
                    if(percentageCompleted == 100){
                        $("#p_custom_message_body").html('<p>Storing training data</p><img src="media/images/loading.gif">');
                    }
                } ;
                return xhr ;
            }

After that update progress bar in another function :-

    function updateUploadPercentage(progress) {
    var elem = document.getElementById("progressBar");
    elem.style.width = progress + '%'; 
    elem.innerHTML = progress * 1 + '%';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM