angular - Angular - 清除文件输入
问题描述
我有一个组件,允许用户填写一些字段以及选择个人资料图片。提交表单后,我正在尝试清除它,以便他们可以添加另一个条目。
组件 HTML:
<input type="file" #userPhoto name="userPhoto" id="userPhoto" (change)="onFileChange($event)" />
组件 TS:
@ViewChild('userPhoto') userPhoto: any;
...
private prepareSave(value): any {
const Image = this.userPhoto.nativeElement;
if (Image.files && Image.files[0]) {
this.userPhoto = Image.files[0];
}
const ImageFile: File = this.userPhoto;
const formData: FormData = new FormData();
formData.append('ParentUserID', value.parentUserID);
formData.append('FirstName', value.firstName);
formData.append('LastName', value.lastName);
formData.append('Age', value.age);
formData.append('Photo', ImageFile, ImageFile.name);
return formData;
}
...
<Submit Form>
clearSelectedPhoto() {
this.userPhoto.nativeElement.value = null;
}
现在,我认为问题在于我viewChild
正在使用any
而不是ElementRef
. 但是,当我更改此设置时,打字稿会在方法中抱怨我的行prepareSave
:
const ImageFile: File = this.userPhoto;
[ts] 类型“ElementRef”不可分配给类型“文件”。“ElementRef”类型中缺少属性“lastModified”。
我如何使用ElementRef
我viewChild
的照片以及File
稍后分配照片?
我试图在我的重置方法中投射它,但看起来也不起作用。
clearSelectedPhoto() {
(<ElementRef>this.userPhoto).nativeElement.value = null;
}
抛出:错误错误:未捕获(承诺):TypeError:无法设置未定义的属性“值”
解决方案
您必须从更改事件中获取文件。
组件 HTML:
<input #userPhoto type="file" (change)="fileChange($event)"/>
组件 TS:
@ViewChild('userPhoto') userPhoto: ElementRef;
private _file: File;
private prepareSave(value): FormData {
const formData: FormData = new FormData();
formData.append('ParentUserID', value.parentUserID);
formData.append('FirstName', value.firstName);
formData.append('LastName', value.lastName);
formData.append('Age', value.age);
formData.append('Photo', this.file, this.file.name);
return formData;
}
fileChange(event) {
this.file = event.srcElement.files[0];
}
clearSelectedPhoto() {
this.userPhoto.nativeElement.value = null;
}
当您使用 TS be shure 在任何地方声明类型时,它可以避免很多错误。不要any
从函数返回。即使您的函数在函数声明 ex: 中返回多个类型指向它getFile(): File | string
。
不要像这样使用相同的变量:
@ViewChild('userPhoto') userPhoto: any;
...
if (Image.files && Image.files[0]) {
this.userPhoto = Image.files[0];
}
在您的代码中,您用文件覆盖了指向输入元素的指针,然后当您尝试清除它的值时,您实际上this.userPhoto.nativeElement.value = null;
写入了Image.files[0].value = null;
.
推荐阅读
- java - 休眠错误:java.lang.ClassNotFoundException:无法加载请求的类
- maven - 来自私人仓库的 Maven 扩展
- kotlin - 如何将 MutableList 添加到另一个 MutableList - Kotlin?
- regex - 有什么方法可以使用 RegEx 从磁力链接或 Flutter / Dart 中的复杂字符串中获取大小信息(MB,GB)?
- python - 我试图让用户在完成后一次又一次地重复while循环
- parallel-processing - F# Array.Parallel.map 不提供并行处理
- arrays - Go中protobuf数组元素的范围
- c++ - 我可以检查是否有任何数据发送到我的服务器而无需等待
- javascript - 如何管理用于在 ReactJS 中显示的 json 属性数组
- google-chrome - 将根证书添加到铬捆绑包