[Fixed] Angular Display the image uploaded immediately after upload

Issue

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?

Solution

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

Leave a Reply

(*) Required, Your email will not be published