Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use FileReader.onload multiple times on a page?

I have a page that has multiple inputs for single file upload. Kind of like this:

<div id="fileUpload1">
    <input id="inputField1" type="file"></input>
</div>
<div id="fileUpload2">
    <input id="inputField2" type="file"></input>
</div>
<div id="fileUpload3">
    <input id="inputField3" type="file"></input>
</div>
<button type="button" onclick="uploadFiles()">Upload</button>

Inside uploadFiles(), I first create an array of each file in the input fields:

var files = [];
for (var i = 1; i <= 3; i++) {
    var element = document.getElementById("inputField" + i);
    var file = element.files[0];
    files.push(file);
}

Then I attempt to call FileReader's onLoad event for each file in the "files" array:

for (var i = 0, f; f= files[i]; i++) {
    var fileName = f.name;
    console.log("out: " + fileName);
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}

addItem() is a function that works.

When I run this, only the last item in the "files" array is uploaded.

If inputField1 has a file named file1.jpg, inputField2 has a file named file2.jpg, etc, I would get the following in the console:

out: file1.jpg
out: file2.jpg
out: file3.jpg
in: file3.jpg
in: file3.jpg
in: file3.jpg

I feel like I am missing something truly fundamental with how to use FileReader. Any help would be appreciated. Thank you!

like image 270
happyshohaku Avatar asked Sep 17 '25 04:09

happyshohaku


1 Answers

<button type="button" onclick="uploadFiles(readF)">Upload</button>

function uploadFiles(){
    var files = [];
    for (var i = 1; i <= 3; i++) {
        var element = document.getElementById("inputField" + i);
        var file = element.files[0];
        files.push(file);
    }
    for (var i = 0, f; f= files[i]; i++) {
        console.log("out: " + fileName);
        readF(f);
    }
}
function readF(f){
    var reader = new FileReader();
    reader.onload = function (e) {
        var fileName = f.name;
        console.log("in: " + fileName);
        addItem(e.target.result, fileName);
    }
    reader.readAsArrayBuffer(f);
}
like image 104
echo Avatar answered Sep 18 '25 17:09

echo