0

I have an input field to accept image

The input field is like this

<input  type="file"  id="photo" accept="image/*" required  @change="UploadPhoto" />

This input field is inside the template of vuejs .The vue version i am using is 3.

I am calling a method UploadPhoto() on uploading an image.

I am trying to encode image to base64

 UploadPhoto() {

  const file = document.querySelector('#photo').files[0];
  const reader = new FileReader();
 
  reader.addEventListener("load", function () {
    
    this.photo=reader.result;    
  //On console.log(this.photo)  here shows base46 encoded value
  
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
 
    console.log('Base 64 of the Upload Photo'+ this.photo);//On console.log(this.photo)  here doesnot shows base46 encoded value instead shows as null
  
  
}
,

I have initialized photo inside data as blank string.

On console.log(this.photo) inside addEventListner() function shows base46 encoded value

On console.log(this.photo) outside addEventListner() function shows base46 encoded value as blank

How to pass baseencode image in addEventListner() function to the outer scope ie this.photo

After the upload of photo i am getting this.photo as null .Base64 of image which is

Midhun Raj
  • 925
  • 2
  • 7
  • 21

1 Answers1

-1

This seems to be an issue with asynchronous calling. An event listener is not fired immediately, and it seems your console.log is run before the listener is fired, making file's value null.

The easiest way is to do the necessary operations to or with your file inside the listener, or call a method to do this from your listener.

If this is not possible, you can make a global variable to store your file in, but you'd need to wait for it to be filled before you can use it.

This page can shed some light on your issue: How to access variable value outside addEventListner method?

Riqk
  • 54
  • 8