角度同时从formData和formGroup发送数据

时间:2018-10-16 08:01:51

标签: node.js angular angular-reactive-forms

是否可以发送带有反应形式的文件(模型驱动)? 文件来自 formData ,另一个数据来自 FormGroup ,如何将其组合并发送到nodejs?

从以下位置获取文件:

<input formControlName="name" class="form-control" type="text">
<input formControlName="surname" class="form-control" type="text">
<input formControlName="email" class="form-control" type="mail">
<input type="file"(change)="addPhoto($event)" />

创建FormControlFormGroup

createFormControls() {
  this.name = new FormControl("", Validators.required);
  this.surname = new FormControl("", Validators.required);
  this.email = new FormControl();
  this.file = new FormControl("");
}

createForm() {
  this.userData = new FormGroup({
    name: this.name,
    surname: this.surname,
    email: this.email,
    file: this.file
  });
}

推送数据

addPhoto(event) {
let target = event.target || event.srcElement;
this.files.push(target.files);
}

将数据发送到节点js

onSubmit() {
  if (this.userData.valid) {
  let filelist: FileList = this.files;
  const formData = new FormData();
  for (let i = 0; i < filelist.length; i++) {
    this.readyFile = filelist[i];
    formData.append('file', this.readyFile[0]);
  }
   // Here I have a main problem - there are "formData" and 
   // "this.userData.value" how send it to together(concat) ?

    this.apiService.updateUserData(--?--)
  }
}

4 个答案:

答案 0 :(得分:0)

在addPhoto内,替换为以下代码。

addPhoto(event) {
  let 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();
    };
  }
}

答案 1 :(得分:0)

在您的pushdata中,更改

this.userData('file').setValue(this.readyFile)

this.userData.get('file').setValue(this.readyFile)

您可以从此file upload in angular

获得更多参考

答案 2 :(得分:0)

问您的问题已经有很长时间了,但是我认为这可以帮助您(或遇到此问题的任何人)

public toFormData<T>( formValue: T ) {
  const formData = new FormData();

  for ( const key of Object.keys(formValue) ) {
  const value = formValue[key];
  formData.append(key, value);
  }

  return formData;
}

onSubmit() {
  if (this.userData.valid) {
    let filelist: FileList = this.files;
    const formData = this.toFormData(this.userData)
    for (let i = 0; i < filelist.length; i++) {
      this.readyFile = filelist[i];
      formData.append('file[]', this.readyFile[0]);
    }
    this.apiService.updateUserData(formData)
  }
}

首先,以FormData的形式获取表单,然后将数组中的每个文件添加到该FormData中(不要忘记“ []”来上传多个文件)

答案 3 :(得分:0)

您可以为要发送的每个FormControl做一个新的formData.append()。

True expected True
True expected True
False expected False
False expected False

我对这种解决方案并不真正满意,但这是我找到的唯一解决方案。 希望能对您有所帮助!