首页 > 解决方案 > 使用角度形式和 ngModel 将文件分配给变量

问题描述

我想使用一个表单将一个文件分配给一个变量,以便我可以将文件发布到我的后端服务器。

我的表格如下所示:

<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
    <label for='file'> Upload </label>
    <input id='file' type='file' name='file' [(ngModel)] = 'uploadedFile' />
    <button type='submit' class='btn btn-basic'> Upload </button>
</form>


{{ uploadedFile ¦ json }}

最后一行仅用于开发目的,允许我查看“uploadedFile”变量的值。

我在我的 TS 文件中将变量简单地定义为:

uploadedFile: any

对于文件以外的任何类型的输入,此方法都有效,因为变量会更新以显示已输入的内容。但是,对于我浏览并选择文件时的文件,变量保持为空。当我单击提交时,我通过将变量“uploadedFile”输出到控制台来确认这一点。但是即使在我选择了一个文件之后,该变量也会返回为“未定义”。必须做什么才能将文件分配给这个 uploadFile 变量?

标签: angularformsfileuploadangular-forms

解决方案


你应该做这个:

html:

<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
    <label for='file'> Upload </label>
    <input id='file' type="file" (change)="onFileChange($event)" />
    <button type='submit' [disabled]="formGroup.invalid || formGroup.prestine" class='btn btn-basic'> Upload </button>
</form>


{{ uploadedFile ¦ json }}

然后在你的 Component.ts

export class CustomComponent {

  formGroup = this.fb.group({
    file: [null, Validators.required]
  });

  constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) {}

  onFileChange(event) {
    const reader = new FileReader();

    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);

      reader.onload = () => {
        this.formGroup.patchValue({
          file: reader.result
       });

        // need to run CD since file load runs outside of zone
        this.cd.markForCheck();
      };
    }
  } 
}

结论:每次上传新文件时,都会更新 FormGroup。

这里还有另一个例子: https ://medium.com/@amcdnl/file-uploads-with-angular-reactive-forms-960fd0b34cb5


推荐阅读