Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert File Object to <img> Angular

In an Angular Component, I have a File like this and its an image:

public file : File;

How to show the image on HTML template, something like this:

<img [src]="file"> 
like image 520
Alexis Brunet Avatar asked Jan 11 '19 15:01

Alexis Brunet


1 Answers

Use FileReader's instance's readAsDataURL method and pass it a File. It has an onload property to which you can assign a handler function. This will be called with event once the input file is read. The event's target.result property will have an encoded URI which you can then use as the image source.

This is how it translates to code

In your Component Class:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  url;

  onChange(event) {
    var reader = new FileReader();

    reader.onload = (event: any) => {
      this.url = event.target.result;
    };

    reader.onerror = (event: any) => {
      console.log("File could not be read: " + event.target.error.code);
    };

    reader.readAsDataURL(event.target.files[0]);

  }

}

And in template:

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

<img *ngIf="url" [src]="url">

Here's a Working Sample StackBlitz for your ref.

like image 149
SiddAjmera Avatar answered Sep 19 '22 21:09

SiddAjmera