Angular 7:如何提交文件/图像以及我的响应式表单?

use*_*497 3 angular angular-reactive-forms angular-forms

我创建了带有文本输入的简单反应式表单,当提交表单时,我想传递来自文件输入的图像。每次我谷歌我得到教程,他们告诉我如何上传文件,但它是在没有其他输入字段的情况下完成的。我明白如何做到这一点,我不明白如何在一次提交中同时提交我的表单和文件输入。

在我的场景中,我不应该使用响应式表单,而是简单地new FormData()将每个输入附加到其中吗?

如果我能做到,请给我一个简单的例子。

编辑:如何在 Angular2 反应形式中包含文件上传控件?这不是答案。回答市场没有随反应形式一起发布文件,它是单独发布文件。

小智 8

也有这个问题,我做的是构造一个FormData,使用循环将formGroup值添加到表单Data

import {
  Component,
  OnInit,
  ChangeDetectorRef
} from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators
} from '@angular/forms';


export class TodoFormComponent {
  todoForm: FormGroup = this.fb.group({
    todo: ['', Validators.required],
    image: ['', Validators.required], //making the image required here
    done: [false]
  })

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

  /**
   *@param event {EventObject} - the javascript change event
   *@param field {String} - the form field control name
   */
  onFileChange(event, field) {
    if (event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      // just checking if it is an image, ignore if you want
      if (!file.type.startsWith('image')) {
        this.todoForm.get(field).setErrors({
          required: true
        });
        this.cd.markForCheck();
      } else {
        // unlike most tutorials, i am using the actual Blob/file object instead of the data-url
        this.todoForm.patchValue({
          [field]: file
        });
        // need to run CD since file load runs outside of zone
        this.cd.markForCheck();
      }
    }

    onSubmit() {
      const formData = new FormData();
      Object.entries(this.todoForm.value).forEach(
        ([key, value]: any[]) => {
          formData.set(key, value);
        }

        //submit the form using formData
        // if you are using nodejs use something like multer
      )
    }

  }
Run Code Online (Sandbox Code Playgroud)
<form [formGroup]="todoForm" (ngSubmit)="onSubmit()">
  <input type="file" formControlName="image" (onchange)="onFileChange($event, 'image')"/>
  <textarea formControlName="todo"></textarea>
  <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

在服务器端,您可以像处理表单数据请求一样处理请求