typescript 对象可能为“null”,ts(2531)|图像选取器

ryoqjall  于 2022-12-19  发布在  TypeScript
关注(0)|答案(3)|浏览(162)

我按照最新的Angular 11,但仍然const file = (event.target as HTMLInputElement).files[0];说:对象可能为空
这是OnInit类:

imagePreview : string | any;
form: FormGroup | any;

这是imagepicker函数:

onImagePicked(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
this.form.patchValue({
  image: file
});
this.form.get('image').updateValueAndValidity();

const reader = new FileReader();
reader.onload = () => {
  this.imagePreview = reader.result as string;
}
reader.readAsDataURL(file);
}

Main code snippets error is looking like this

ecr0jaav

ecr0jaav1#

尝试使用if语句检查文件是否存在。

onImagePicked(event: React.FormEvent) { //use any if even React.FormEvent doesn't work
   if(event.target.files){
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      image: file
    });
  ...
}
zed5wv10

zed5wv102#

只不过HTMLInputElement文件类型如下:文件列表||null,所以我假设File也是null,代码如下所示。

onPickImage(event: Event){
const file = (event.target as HTMLInputElement).files?.[0];
this.form.patchValue({
  image : file
});
this.form.get('image')?.updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
  this.imagePreview = reader.result;
};
reader.readAsDataURL(file)

}

hgncfbus

hgncfbus3#

onImagePicked(event: any) {
    const file = (event.target as HTMLFormElement).files[0];
    this.form.patchValue({
    image: file
    });
    this.form.get('image').updateValueAndValidity();
    const reader = new FileReader();
    reader.onload = () => {
    this.imagePreview = reader.result as string;
    }
    reader.readAsDataURL(file);
}

这对我很有效:)

相关问题