我正在尝试手动将数据从FileReader设置为控制值("图像")。当我将"reader.result"(存储二进制图像数据)设置为"图像"FormControl时,我收到一个错误:
错误 DOMException:无法在"HTMLInputElement"上设置"value"属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。
我的组件:
formInitBuilder() {
this.formProducts = this.fB.group(
{
name: new FormControl('', Validators.required),
description: new FormControl(''),
detailedDescription: new FormControl(''),
price: new FormControl('', Validators.minLength(1)),
isNewProduct: new FormControl(true),
promotionalProduct: new FormControl(true),
categoryId: new FormControl('', Validators.required),
image: new FormControl('', Validators.required)
});
}
uploadImage(file: FileList) {
this.fileToUpload = file.item(0);
let reader = new FileReader();
console.log(reader.result);
reader.onload = (event: any) => {
this.formProducts.controls['image'].setValue( reader.result);
};
reader.readAsDataURL(this.fileToUpload);
}
模板:
<div class="form-group">
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" #Image accept="image/*"(change)="uploadImage($event.target.files)" class="custom-file-input" id="inputGroupFile02" formControlName="image">
<label class="custom-file-label" for="inputGroupFile02">Select image</label>
</div>
</div>
</div>
我想将二进制图像数据保存在表单控件图像中。
formBuilder (docs) 时不要使用 new FormControl()
,它应该是这样的:
this.formProducts = this.fb.group({
name: ['', Validators.required],
description: [''],
});
删除formControlName="image"
(顺便说一下,它应该是[form]="formProducts"
父级的子级),因为您已经在uploadImage()
方法中将输入值"链接"到 FormGroup,并且因为,如错误消息中所述,这会尝试设置 value
属性而不是 filename
。
如果你想做你自己的FileInputValueAccessor指令,你可以看看这个答案。