如何在 angular 6 中使用 Reactive 表单将 FormData 与另一个 FormControl 一起发送?

How to send FormData with another FormControl using Reactive form in angular 6?

我使用 angular 的反应形式制作了一个包含电子邮件用户名和头像等字段的表单 6. 我知道我需要表单数据来上传图像,但我不知道如何使用反应形式在 angular 6. 任何人都可以帮忙吗?

试试这个:

<form [formGroup]="yourForm" (ngSubmit)="onSubmit()">
   <input type="text" formControlName="email"> <br>
   <input (change)="uploadDocument($event)" type="file" accept=".png, .pdf, .jpg, .jpeg"> <br>
   <input (change)="onSubmit()" type="submit" value="Send file">
</form>

在您的 app.component.html 中,然后:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  yourForm: FormGroup;

  constructor(private fb: FormBuilder, private http: HttpClient) {
    this.yourForm = this.fb.group({
      email: [''],
      file: ['']
    });
  }

  uploadDocument(event: any) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      reader.onload = () => {
        this.yourForm.get('file').setValue(event.target.files[0]);
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }

  onSubmit(): void {
    const uploadData = new FormData();
    uploadData.append('email', this.yourForm.get('email').value);
    uploadData.append('file', this.yourForm.get('file').value);
    this.http.post('your-route', uploadData);
  }
}

在您的 app.component.ts 中,并且:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

在您的 app.module.ts 文件中。 另外,不要忘记在 this.http.post('your-route', uploadData);.

行配置路由