Skip to content Skip to sidebar Skip to footer

Javascript Base64 Encoding Function Returns Undefined

I am attempting to add Base64 encoded images to a string array. Using a file input form created with react-bootstrap's FormControl:

Solution 1:

No value is returned from getBase64 function synchronously from within an event handler which provides results asynchronously. FileReaderloadend event returns results asynchronously. You can use Promise.all() or async/await to get value returned asynchronously from getBase64() function call

classReadFiles {
  constructor() {}
  asyncaddImage(event) {
    const newArr = [];
    for (let i = 0; i < event.target.files.length; i++) {
      newArr.push(
        awaitthis.getBase64(event.target.files[i])
      );
    }
    const o = {
      files: newArr
    };

    console.log(o);
  }

  getBase64(file) {
    returnnewPromise(function(resolve) {
      var reader = newFileReader();
      reader.onloadend = function() {
        resolve(reader.result)
      }
      reader.readAsDataURL(file);
    })
  }

}

let reader = newReadFiles();

document.querySelector("input[type=file]")
.onchange = e => reader.addImage.call(reader, e);
<inputtype="file"multiple>

Post a Comment for "Javascript Base64 Encoding Function Returns Undefined"