Angular2 file input onchange

故事扮演 提交于 2019-11-30 17:24:31
Double H

Use the following in your template:

<div class="modal-body">
   <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
   <img id="preview" src="" alt="Preview">
</div>

Then your Component fileChangeEvent() as

public fileChangeEvent(fileInput: any){
      if (fileInput.target.files && fileInput.target.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e : any) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

All Your File related info will console....

Here's my amendments to Double H's answer to not rely on jQuery and stop the webpack erroring out on e.target.result.

<img [src]="imageSrc" alt="" />
<input type="file" capture="camera" accept="image/*" (change)="displayPhoto($event)">

Typescript Code

displayPhoto(fileInput) {
  if (fileInput.target.files && fileInput.target.files[0]) {
  const reader = new FileReader();

  reader.onload = ((e) => {
    this.imageSrc = e.target['result'];
  });

  reader.readAsDataURL(fileInput.target.files[0]);
}

}

Double H's function didn't work for me till I added onclick="this.value = null" as found here: https://stackoverflow.com/a/42357862/634650

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