Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get path from file upload input in angular 4

I want to upload an image and create a preview of it in angular 4.
The template is given below:

<div>
  <input type="file" (onchange)="handleUpload($event)">
  <img [src]="Logo" >
</div

I want to call a function handleUpload() whenever a file is chosen. This function sets the value of the variable Logo to the path of the file chosen. I am not able to get the path because the function handleUpload($event) is not called.
The component class is given below:

 export class App {
 Logo:string;

 handleUpload(e):void{
    this.Logo = e.target.value;

 }

  constructor() {

  }
}

I don't understand what is wrong with my code. Demo

like image 292
Gadheyan .t.s Avatar asked May 23 '17 08:05

Gadheyan .t.s


2 Answers

In angular you write javascript events without the "on" suffix.

Change:

<input type="file" (onchange)="handleUpload($event)">

To:

<input type="file" (change)="handleUpload($event)">
like image 107
unitario Avatar answered Oct 09 '22 21:10

unitario


Show preview image - Example code

<input type="file" (change)="showPreviewImage($event)">
<img [src]="localUrl" *ngIf="localUrl" class="imgPlaceholder">



 localUrl: any[];
    showPreviewImage(event: any) {
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.localUrl = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
    }

Demo and more info

like image 24
Prashobh Avatar answered Oct 09 '22 20:10

Prashobh