无法设置未定义角度的属性

问题描述 投票:0回答:1

我有一个包含一些属性的模型,其中一个是文件类型的“ Upload”。我也使用输入元素从计算机中选择图像。更改图像和预览事件的效果很好,但是,当我尝试将文件结果设置为文件类型的“上传”时,它返回错误“无法设置属性“未定义”的“上传”。将文件设置为属性“ Upload”后,我也尝试记录该文件,并引发相同的错误。

这是我的模型的样子:

{
 creatorId: number; 
Upload: File; //for image upload to server
}

这是我的图片更改事件

  preview(files: any) {
    if (files.length === 0) return;

    var mimeType = files[0].type;
    if (mimeType.match(/image\/*/) == null) {
      this.commonservice.showToastError("Only images are supported.");
      return;
    } else {
      var reader = new FileReader();
      this.logo = files[0];
      this.formData.Upload = this.logo; //throws error on this line
      reader.readAsDataURL(files[0]);
      reader.onload = _event => {
        this.imgURL = reader.result;
        this.message = files[0].name;
      };
    }
  }

这是我的component.html

  <input
                    #file
                    style="width: 0.1px; height: 0.1px;  opacity: 0;overflow: hidden; position: absolute; z-index: -1;"
                    type="file"
                    name="imgfile"
                    id="imgfile"
                    (change)="preview(file.files)"
                    accept="image/*"
                    formControlName="Upload"
                  />

我在做什么错?我需要将预览事件中的转换结果设置为formData中的“ Upload”属性。我也曾尝试在init或存储值之前初始化一个新文件,结果却一样。谢谢

javascript angular typescript file image-uploading
1个回答
0
投票
html

      <input
        #file="ngModel"
        name="file"
        type="file"
        class="form-control"
        (change)="preview($event)"
      />

ts

  preview($event: any) {
    const files = ($event.target as HTMLInputElement).files;
    // files is an array

    ... do your thing
  }
© www.soinside.com 2019 - 2024. All rights reserved.