Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 encode image to base64

I want to encode the uploaded files to base64 so that I can pass them to the request. The problem is that I'm using Angular 2 with Typescript and I couldn't find any info on how to do that. I found that in Javascript it can be done with canvas but I don't know how could I implement the code in Typescript.

<input type="file" class="form-control" accept="image/*" multiple     [(ngModel)]="spot.images" name="images"> 
like image 978
Mantas Avatar asked Sep 01 '16 13:09

Mantas


Video Answer


1 Answers

So I find the solution:

compontent.ts

changeListener($event) : void {   this.readThis($event.target); }  readThis(inputValue: any): void {   var file:File = inputValue.files[0];   var myReader:FileReader = new FileReader();    myReader.onloadend = (e) => {     this.image = myReader.result;   }   myReader.readAsDataURL(file); } 

component.html

<input type="file" accept="image/*" (change)="changeListener($event)"> 
like image 143
Mantas Avatar answered Sep 18 '22 14:09

Mantas