角度上传后立即显示上传的图片

时间:2019-11-07 09:51:59

标签: angular typescript

在尝试以成角度的方式使用输入文件上传后,我试图立即显示上传的图像。

我正试图从打字稿文件中获取网址,以在html文件中显示该网址:

<img src={{url}}>

我有这样的文件:
html:

  <input type="file" (change)="onFileChanged($event)" >

ts:

  onFileChanged(event) {
    this.selectedFile = event.target.files[0]
    console.log(this.selectedFile)
  }

我该如何获取图像并将其显示为immedetialey?

2 个答案:

答案 0 :(得分:2)

onFileChanged(event) {
    const files = event.target.files;
    if (files.length === 0)
        return;

    const mimeType = files[0].type;
    if (mimeType.match(/image\/*/) == null) {
        this.message = "Only images are supported.";
        return;
    }

    const reader = new FileReader();
    this.imagePath = files;
    reader.readAsDataURL(files[0]); 
    reader.onload = (_event) => { 
        this.url = reader.result; 
    }
}

答案 1 :(得分:0)

 onFileChanged(e) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.url = reader.result; 
      };
    }
  }