Reputation: 3
I am trying to use filereader to read data of multiple files in an array. But there is an error saying The object is already busy reading Blobs.
flag = 1;
var file;
var fileRead = [];
for (var i = 0, f; f = changeEvent.target.files[i]; i++) {
reader.onload = function(loadEvent) {
scope.$apply(function() {
if (flag == 1) {
fileRead.push(loadEvent.target.result);
}
});
};
reader.readAsDataURL(f);
}
for (i = 0; i < changeEvent.target.files.length; i++) {
file = changeEvent.target.files[i];
fileName.push(file.name);
}
}
}
i have tried using a loop to see if that operation is done but it ends up in an infinite loop.
Upvotes: 0
Views: 5467
Reputation: 101
You can create an object to each file. Try this:
inputFile.addEventListener("change", (event) => {
[...event.target.files].forEach(file => {
const reader = new FileReader()
reader.addEventListener('load', event => {
console.dir(event.target.result);
});
reader.readAsText(file);
});
}, false);
Upvotes: 0
Reputation: 1008
Here's a snippet of what worked for me. readAsDataURL is async so you have to wait for the file to read before working on the next one. Make sure you declare the reader within the loop.
var files = e.target.files;
if(files) {
for (let i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onloadend = function(output){
console.log('output', output.target.result)
console.log('fileNamnes', f.name)
}.bind(this);
reader.readAsDataURL(f)
}
}
Upvotes: 2
Reputation: 16068
You need to wait for the reader to finish reading, filereader is async so you can't do that in the for. Haven't tried it, but here is how to do it:
function readFiles() {
if (changeEvent.target.files.length > 0) { // if we still have files left
var file = changeEvent.target.files.shift(); // remove first from queue and store in file
reader.onloadend = function (loadEvent) { // when finished reading file, call recursive readFiles function
fileRead.push(loadEvent.target.result);
readFiles();
}
reader.readAsDataURL(file);
} else {
finishedReadingFiles() // no more files to read
}
}
readFiles();
Upvotes: 3