angularangular9angular-file-upload

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


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="">

Solution

  • 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">