在同一个请求中发送 Reactive Form 和图片

Send Reactive Form and picture in the same request

我有一些字段的响应式表单:

this.pointForm = new FormGroup({
  X_WGS84: new FormControl(null, Validators.required),
  Y_WGS84: new FormControl(null, Validators.required),
  country: new FormControl(null),
  state: new FormControl(null),
  ... etc

在 onSubmit 方法中,我将表单中的字段分配给 class 点:

export class Point {
  X_WGS84: number;
  Y_WGS84: number;
  country?: string;
  state?: string;
  ... etc

但是我不知道,如何在同一个请求中发送表单数据和图像。

    onSubmit() {
    if (this.pointForm.valid) {
      Object.keys(this.pointForm.value).forEach(key => {
        this.point[key] = this.pointForm.value[key] === '' ? null : this.pointForm.value[key];
      });
      this.httpService.addPoint(this.point, this.fileToUpload).subscribe(
        point => {
          this.router.navigate(['/home']);
        },
        error => {
          console.log(error.statusText);
        });
    }
}

我做了类似的事情:

constructor(private http: HttpClient) {}

addPoint(point: Point, fileToUpload: File): Observable<Point> {
    const formData: FormData = new FormData();
    formData.append('image', fileToUpload, fileToUpload.name);
    formData.append('Point', point);
    return this.http.post<Point>('http://localhost:8000/point/new', formData);
  }

但是:

发送此类请求的正确方法是什么?

函数append(),我用来发送这个请求,要求类型为Blob或string。我发送对象,所以我应该将其更改为 JSON 字符串。 现在它可以正常工作了。

    addPoint(point: Point, fileToUpload: File): Observable<Point> {
        const formData: FormData = new FormData();
        formData.append('image', fileToUpload, fileToUpload.name);
        formData.append('Point', JSON.stringify(point));
        return this.http.post<Point>('http://localhost:8000/point/new', formData);
  }