Search code examples
angularangular-componentsangular11angular-input

Cannot read properties of undefined reading base64 - Angular


I have input field to upload image

<div class="form-group">
  <label for="exampleFormControlInput1">
    Upload Image
  </label>
  <input #imageInput type="file" accept='image/*' class="form-control" (change)="onChange($event)"
  />
</div>
<div class="pb-4 form-group float-right">
  <button class="btn btn-primary btn-main" (click)="saveImage()">
    Save
  </button>
  &nbsp;
  <button class="btn btn-primary btn-cancel">
    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


Solution

  • 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')
          });
        };
      }