1

I have the following code in which I'm trying to read a file using FileReader and put its contents in an array. Only after all the data has been pushed do I want to continue. Here's what I have currently:

    const confirm = () => {

        var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
        };
        reader.readAsDataURL(formValues.images[0].file);
        console.log('images base 64');
        console.log(images); // this prints the empty array. 

    };

I want to continue on only after images have been updated with the file contents. How can I do that?

-- edit --

I want to in fact add multiple files to the array, so I tried the following.

    var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
            console.log('images base 64');
            console.log(images);
        };
        for (let i = 0; i < formValues.images.length; i++) {
            reader.readAsDataURL(formValues.images[i].file);
        }

But this gives the error "InvalidStateError: The object is in an invalid state."

zengod
  • 1,114
  • 13
  • 26

2 Answers2

2

You are trying to the result before it load. Move the console.log(images) inside onload function.

const confirm = () => {
        var reader = new FileReader();
        let images = [];
        reader.onload = function(e) {
            images.push(e.target.result);
             console.log(images);
        };
        reader.readAsDataURL(formValues.images[0].file);
        console.log('images base 64');          
    };
Ivan-San
  • 771
  • 1
  • 5
  • 22
Joe
  • 365
  • 2
  • 9
  • 24
  • This was just an example where I gave a single image, i.e., formValues.images[0].file. In reality, formValues.images contains multiple files. How will I push all the files into the images array? – zengod Jan 10 '20 at 22:05
  • Loop through it and have some flag for check for the last one. – Joe Jan 10 '20 at 22:08
  • Check this. https://stackoverflow.com/questions/13975031/reading-multiple-files-with-javascript-filereader-api-one-at-a-time – Joe Jan 10 '20 at 22:15
  • try like this , ti works for me reader.onloadend =(e) =>{ var result = reader.result; this.file64.push(result) }; – achref akrouti Sep 21 '20 at 10:01
0

it works for me try like this , surly

this.file64=[];
    reader.onloadend =(e) =>{
                

                  var result = reader.result; 
                      console.log(result)
                      this.file64.push(result)
                };
achref akrouti
  • 575
  • 1
  • 6
  • 21