Angular 9 "Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. "

2.6k views Asked by At

I have this problem when i am trying to display selected image before upload image

enter image description here

company.component.ts

handleFileInput(file: File){

    console.log(file);

    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = event => {
      this.imageUrl = event.target.result;
      console.log(this.imageUrl);
    };

  }

HTML

<input
  type="file"
  #fileInput
  (change)="handleFileInput(fileInput.files[0])"
/>

<img [src]="imageUrl" height="50px" alt="">
2

There are 2 answers

4
Rafi Henig On BEST ANSWER

The following is an example of how it might be implemented:

Component:

public imageUrl : SafeResourceUrl;

constructor(private sanitizer: DomSanitizer) { }

public upload(list: FileList): void {
  const urlToBlob = window.URL.createObjectURL(list.item(0)) 
  this.imageUrl = this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); 
}

Template:

<input type="file" (change)="upload($event.target.files)">

<img [src]="url">
0
Prakash Harvani On

Try it.

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

constructor(
    private dtr: ChangeDetectorRef,
  ){
    
  }
handleFileInput(event) {

    if (event.target.files && event.target.files[0]) {

        this.imageFile = event.target.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(event.target.files[0]);
        reader.onload = () => {
          this.url = reader.result;
              this.dtr.detectChanges();

        };
      } 

in Html file.

 <input type="file" accept=".png, .jpg, .jpeg" (change)="handleFileInput($event)"> 

<img [src]="url">