skip to Main Content

all I’m getting this typerror, and I can’t figure it out. I’ve searched Google, but I can’t seem to find an answer.

TypeError: Argument 1 (‘blob’) to FileReader.readAsDataURL must be an
instance of Blob

here is my component method:

onFilePick(event: Event) {
    const file = (event.target as HTMLInputElement).files;
    //console.log(file);
    // console.log(this.form);
    this.form.patchValue({ Image: file });
    this.form.get('image')?.updateValueAndValidity();
    const reader: any = new FileReader();
    reader.onload = () => {
      this.imagePreview = reader.result;
    };
    return reader.readAsDataURL(file);
  }

2

Answers


  1. From a quick glance it looks like file will be an array of blobs.

    Change const file = (event.target as HTMLInputElement).files;
    to
    const file = (event.target as HTMLInputElement).files[0]; to get the first file by index.

    You might want to check that a file exists as well. Something like

    const files = (event.target as HTMLInputElement).files;
    const file = files[0];
    
    if(!file){
        return;
    }
    
    Login or Signup to reply.
  2. The typings provided by TypeScript are not ideal here. The HtmlInputElement‘s files has the type FileList which is an array of Files. However, at the same time, those files are also an instance of Blob, but the TypeScript compiler does not know about it.

    To fix it, add a check if the file is an instance of Blob:

    onFilePick(event: Event) {
      const file = (event.target as HTMLInputElement).files?.[0];
      if (!(file instanceof Blob)) {
        throw new Error('File is not a blob');
      }
      this.form.patchValue({ image: file });
      this.form.get('image')?.updateValueAndValidity();
      const reader = new FileReader();
      reader.onload = () => {
        this.imagePreview = reader.result;
      };
      return reader.readAsDataURL(file);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search