Angular 17中使用FileReader()出现TypeError问题求助
解决Angular 17中FileReader.readAsDataURL的TypeError问题
问题原因
报错TypeError: Argument 1 ('blob') to FileReader.readAsDataURL must be an instance of Blob的核心原因是:你从input元素获取的files是FileList对象(类数组结构,包含选中的所有文件),而readAsDataURL方法要求传入单个Blob或File实例,直接传入FileList会不符合参数类型要求。
修正后的代码
onFilePick(event: Event) { const inputElement = event.target as HTMLInputElement; // 获取第一个选中的文件,同时做存在性检查 const selectedFile = inputElement.files?.[0]; if (!selectedFile) return; // 没有选中文件时直接返回,避免后续错误 // 表单赋值时传入单个文件,而非FileList this.form.patchValue({ Image: selectedFile }); this.form.get('image')?.updateValueAndValidity(); const reader = new FileReader(); reader.onload = () => { this.imagePreview = reader.result as string; }; // 传入单个File实例给readAsDataURL reader.readAsDataURL(selectedFile); }
关键修改点
- 获取单个文件:用
inputElement.files?.[0]获取用户选中的第一个文件,同时通过可选链操作符?.避免files为null时的报错。 - 增加空值检查:判断
selectedFile是否存在,防止用户未选择文件就触发事件导致后续逻辑报错。 - 表单赋值修正:表单控件
Image应该接收单个文件对象,而非FileList,这样符合表单值的预期类型。 - 类型规范:去掉
reader: any的任意类型声明,使用默认的FileReader类型,同时将reader.result断言为string,符合Angular的类型检查要求。
内容的提问来源于stack exchange,提问作者Zayno lane
相关产品推荐
相关产品推荐

