AliAb
AliAb

Reputation: 569

Show uploaded image immediately after upload in angular

I'm trying to show an uploaded image immedetialy after using input file upload in angular.

I was trying to get the url from the typescript file to show it like that in html file:

<img src={{url}}>
             

I'm having the file like that:
html:

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

ts:

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

What do I do to get the image and show it immedetialey?

Upvotes: 9

Views: 19991

Answers (2)

Sourav Golui
Sourav Golui

Reputation: 633

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

Upvotes: 14

Jayakumar Thangavel
Jayakumar Thangavel

Reputation: 2005

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

Upvotes: 4

Related Questions