Angular: 提交带有数据和图像的表单

Angular: Submit form with data and image

我有一个模板驱动的表单,其中包含一些字段(例如姓名、生日、地点等)。还应上传图像。并非所有字段都是必需的。

我用 formData 对象试过了。每个字段都将添加如下: fileUploadForm.append('place', this.model.place); 如果 place-field 有输入,这会起作用。如果它是空的,我有一个 "undefined".

使用 formData 对象是正确的还是有其他方法? 如何只向 formData 对象添加填充的字段?

export class CreateComponent implements OnInit {
model: any = {};

fileChanged(event) {
    this.file = event.target.files[0];
  }

onSubmit() {
    let fileUploadForm: FormData  = new FormData();
    fileUploadForm.append('picture', this.file);
    fileUploadForm.append('name', this.model.name);
    fileUploadForm.append('birthday', this.model.birthday);
    ...
 this.CreateService.setData(fileUploadForm)
    .subscribe(
    ...
}

}

您可以使用 if 语句,例如 if (this.file) fileUploadForm.append('picture', this.file);。最好的方法是使用 angular 反应形式检查这个 slackblitz 示例 angular reactive form