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
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
The typings provided by TypeScript are not ideal here. The
HtmlInputElement
‘s files has the typeFileList
which is an array ofFile
s. However, at the same time, those files are also an instance ofBlob
, but the TypeScript compiler does not know about it.To fix it, add a check if the file is an instance of
Blob
: