ANGULAR 4 Base64 Upload Component

我的未来我决定 提交于 2019-12-05 05:55:47

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

To answer your exact question...

Is there a Angular component or directive for the that would bind the base64 to the said model?

No. It's out of scope of Angular. You can use common ways of encoding data into base64.

You can then create a control value accessor that would take care of conversion, to keep your code more DRY.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!