Why does FileReader.readAsText() throw an Uncaught DOM Exception when multiple files are trying to be read?

Viewed 103

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.

1 Answers
  • I know promises don't make asynchronous tasks synchronous
  • Figured out a solution to the problem
  • Tried promises and it did not work well for me, but I may just not have done it right

I'd still love a promise solution if anyone has one.

How to await the FileReader object without Promises

Related