简体   繁体   中英

javascript how to make a progress bar for each file

I have written a pure javascript ajax uploader.

Here you see the progress event attached to an element. How is it possible to loop through the file arrays and then show one progress bar for each of them?

Here is the part of the code that deals with the progress-event:

`request.upload.addEventListener('progress', function(event){ var progress = document.getElementById('progressBar');

    if(event.lengthComputable)
    {                       

        // get the loaded amount in decimals. For instance: if 50kbs of a 100kbs file is loaded, it equals 0.5
        var percent = event.loaded / event.total;

        // now fill in the progressBar div with a dynamic percentage change. 
        if(progress.hasChildNodes())
        {
            progress.removeChild(progress.firstChild);  
        }

        progress.appendChild(document.createTextNode(Math.round(percent*100)+" %")); // this converts the decimals to a integer number between 0-100 representing the percentage. 
    }`

And this is my file arrays (i need to create an individual progress bar for each file selected by user, because this upload allows multiple file selection):

var file = document.getElementById('file');

    // assigning a new FormData
    var data = new FormData();

    // now append selected files to the data object
    for(var i = 0; i < file.files.length; ++i)
    {
        // append each file to the data object
        data.append('file[]', file.files[i]);   
    }

Don't remove/create for every progress update. Just change the width of a div to show progress:

<div style="border:1px solid #000;background-color:#fff;width:200px;">
    <div id="progress" style="width:0%;"></div>
</div>

Now on progress event, just changed the width % of $("#progress"). Or just replace the innerHTML of it if you're showing a string "65% done"

For each value of i, create a copy of the progress indicator and put it in an array so it is at position i. If you won't know the index when you need to update, use an object or give them IDs so you can find the right one to update.

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