ANGULAR 4 Base64 Upload Component

Vijayavel picture Vijayavel · Jan 11, 2018 · Viewed 21.6k times · Source

I am new to Angular. I am using Angular 4. Where there is a requirement to send the base64 Image as one of the model member to the web api. Is there a Angular component or directive for the that would bind the base64 to the said model?

Appreciate and Thank you for the help.

Answer

Arnaf Aziz picture Arnaf Aziz · Jan 12, 2018

You can upload image and store it as base64 encoded.

In your template add this

<div class="image-upload">
    <img [src]="imageSrc" style="max-width:300px;max-height:300px"/>
    <input name="imageUrl" type="file" accept="image/*" (change)="handleInputChange($event)" />
</div> 

And this will handle your upload mechanism from component

  private imageSrc: string = '';

  handleInputChange(e) {
    var file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];
    var pattern = /image-*/;
    var reader = new FileReader();
    if (!file.type.match(pattern)) {
      alert('invalid format');
      return;
    }
    reader.onload = this._handleReaderLoaded.bind(this);
    reader.readAsDataURL(file);
  }
  _handleReaderLoaded(e) {
    let reader = e.target;
    this.imageSrc = reader.result;
    console.log(this.imageSrc)
  }

You can also use this code to make a component to upload an image