Angular2 file input onchange

假装没事ソ 提交于 2019-12-30 05:50:06

问题


I have input file (without submit - typicall input file). I'd like to call some function when chose file.

Example: I click on "Choose file" -> choose file -> now system detects change and call some function which prints all these file information (for example image name).

I can't use ngModel on input file, right? How to do that?


回答1:


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....




回答2:


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]);
}

}




回答3:


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



来源:https://stackoverflow.com/questions/38476315/angular2-file-input-onchange

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