TLDR; Wanted to make a text editor, made it, now I'm trying to have an upload feature.
I want to read every file as text, and I'm not sure I'm doing it right.
This is my script :
function main() {
$('#imported-files').on('change', function() {
var files = this.files,
reader = new FileReader();
console.log(typeof(files))
reader.onload = function(e) {
console.log(e.target.result);
}
for (let i = 0, numFiles = files.length; i < numFiles; i++) {
const file = files[i];
reader.readAsText(file)
}
})
}
$(document).ready(main);
YES the input tag is multiple, and accepts all file types. I get the change event and get the files and a new FileReader obj. Once loaded, it reads the files results.
This works with a single uploaded file
But when the for loop has more than one file in the files list, it throws an error because it's reading a file already.
Possible solutions that I couldn't justify doing:
- Make a new FileReader with every loop, seems solid for small list of files, but not best practice
- Write a promise for the reader so it becomes a synchronous action and then continues in the loop
I also don't know the FileReader API that well, but reading through the Mozilla site, I see it has different functions to check the state of the file reader. If anyone could shed some light that'd be awesome.