Home > Software design >  Cannot read properties of undefined reading base64 - Angular
Cannot read properties of undefined reading base64 - Angular

Time:07-29

I have input field to upload image

<div >
  <label for="exampleFormControlInput1">
    Upload Image
  </label>
  <input #imageInput type="file" accept='image/*'  (change)="onChange($event)"
  />
</div>
<div >
  <button  (click)="saveImage()">
    Save
  </button>
  &nbsp;
  <button >
    Cancel
  </button>
</div>

Here's where i catch event when file is uploaded then save.

onChange(event) {
  this.imageChangedEvent = event;
}

saveImage() {
  console.log(this.selectedPicture) this.apiService.postData('educational-award/', {
    "photo": this.selectedPicture.base64,
    "id": this.educationalData.id
  }).subscribe(data = >{
    console.log('test')
  });
}

But when i console.log(this.selectedPicture) it gives me undefined

enter image description here

CodePudding user response:

Your function does not read the base64 file format. This should work based on your example.

Controller:

async onChange(files: File[]) {
    const file = files[0];
    this.selectedPicture = await this.fileToBase64(file);
}

async fileToBase64(file: File) {
    return new Promise<string | Error>((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async () => resolve(reader.result as string);
        reader.onerror = async (reason) => reject(reason);
    });
}

saveImage() {
  this.apiService.postData('educational-award/', {
    photo: this.selectedPicture,
    id: this.educationalData.id
  }).subscribe(data = > {
    // do whatever, throw toaster etc.
  });
}

Template:

  <input #imageInput type="file" accept='image/*'  (change)="onChange($event.target.files)">

CodePudding user response:

You can try this:

onChange(event) {
    this.imageChangedEvent = event.target.files[0];
  }

  saveImage() {
    const file = this.imageChangedEvent;
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      this.apiService.postData('educational-award/', {
        "photo": reader.result,
        "id": this.educationalData.id
      }).subscribe(data => {
        console.log('test')
      });
    };
  }
  • Related