0

I've been triying to return a string in a reader.onloadend but it keeps me returning my entire function.

my function below:

uploadFile() {
      let vm = this;
      var file = vm.$refs["testeLogo"].files[0];
      var reader = new FileReader();
      reader.onloadend = function() {
        console.log(reader.result); // returns me a string base64
        document.querySelector("#supe").setAttribute("src", this.imagem);
        return reader.result;
      };
      reader.readAsDataURL(file);
    }

How can I return the value of the string in a proper way, because it keeps returning my own function instead of the reader.result that is printed on the console.log

Sylleth
  • 25
  • 1
  • 5

1 Answers1

-1

Assuming you are working on a Vue app (let me know if don't):

Just use the imageBase64 variable wherever you want in your template, it will be updated once the file is loaded.

data () {
  return {
    imageBase64: ''
  }
},

methods: {
  uploadFile() {
    let vm = this;
    var file = vm.$refs["testeLogo"].files[0];
    var reader = new FileReader();

    reader.onloadend = function() {
      document.querySelector("#supe").setAttribute("src", this.imagem);
      
      vm.imageBase64 = reader.result
    };

    reader.readAsDataURL(file);
  }
}

Also remember to not query the DOM directly using Vue, you can directly bind imagem variable to the img src attribute:

<img :src="imagem" alt="" />
Sergio Cerrutti
  • 395
  • 1
  • 9