Home > Software engineering >  Can I append FormGroup to FormData to post multiple inputs having plain text and files?
Can I append FormGroup to FormData to post multiple inputs having plain text and files?

Time:10-08

1 If I have a signup form as FormGroup which have multiple inputs for plain text as well as files/images. Can I append that form to FormData()? If yes then how can I retrieve fields data because the formData Object I've created posts empty which throws error that "User Request Format is incorrect".

CodePudding user response:

hope this helps ,also you cant see formdata with console.log you need to do a for-of on the formdata instance to see the values

 uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file,
    });
    this.form.get('avatar').updateValueAndValidity();
  }
  submitForm() {
    var formData: any = new FormData();
    formData.append('name', this.form.get('name').value);
    formData.append('avatar', this.form.get('avatar').value);
    this.http
      .post('http://localhost:4000/api/create-user', formData)
      .subscribe({
        next: (response) => console.log(response),
        error: (error) => console.log(error),
      });
  }

  • Related