Siva Charan
Siva Charan

Reputation: 105

mutiple file upload progressbars with javascript

I want to upload multiple files and want to show their progress.I am trying the following code. Here is my html code...

<div id='albumBox'>
    <input type='file' multiple name='newsfeedAlbum[]' id='newsfeedAlbum' onchange='uploadNewsfeedImages()' />
<div>
<div id='uploadingImages'>
</div>
<div>
    <preogress id='progressBar'> </progress>
</div>
<div>
    <input type='button' id='albumButton' value='post' disabled />
</div>

here is my javascript code...

function uploadNewsfeedImages()
{
    alert(document.getElementById("newsfeedAlbum").files.length);
    var files = document.getElementById("newsfeedAlbum").files;
    for(var i = 0;i < files.length;i++)
    {
        var file = files[i];
        //alert("file name is "+files.item(i).name);
        var formData = new FormData();
        formData.append("image",file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST","add_newsfeed.php",true);
        alert(i);
        xhr.upload.onprogress = function()
        {
            alert("bujji" + i);
        }
        xhr.send(formData);
    }
}
function showUploadProgress(event)
{
    var uploaded = event.loaded/event.total;
    uploaded = Math.floor(uploaded*100);
    document.getElementById("progressBar").value = uploaded;
}

But when I am trying to upload two images and alerting on upload.progress event it is alerting bujji2 and bujji2 instead of bujji0 and bujji1.How to handle individual upload.progress events....

Upvotes: 1

Views: 54

Answers (2)

befzz
befzz

Reputation: 1292

You need to save your i, because it will be changed before onprogress fired.

    xhr.upload.fileNum = i;
    xhr.upload.onprogress = function()
    {
        alert("bujji" + this.fileNum);
    }
    xhr.send(formData);

And read explanation for previous answer: Creating_closures_in_loops.3A_A_common_mistake

Upvotes: 1

Shilly
Shilly

Reputation: 8589

It's a scope issue. The for loop will have completed by the time the onprogress events will trigger, so 'i' will be 2 every time the onprogress triggers because your 'for-loop' has finished running.

You can wrap the onprogress function in a closure to get the desired effect.

xhr.upload.onprogress = (function() {
    return function() {
        alert('bujji' + i);
    };
}());

Upvotes: 2

Related Questions