1

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....

0

2 Answers 2

2

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); }; }()); 
Sign up to request clarification or add additional context in comments.

1 Comment

how to achieve multiple file upload progress bars with html5 and javascript
1

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

1 Comment

how to achieve multiple file upload progress bars with html5 and javascript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.