首页 > 解决方案 > 在同一个请求中发送 Reactive Form 和图片

问题描述

我有一些字段的反应形式:

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 方法中,我将表单中的字段分配给 Point 类:

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);
  }

但:

错误

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

标签: filepostangular5httpclientangular-reactive-forms

解决方案


我用来发送此请求的函数 append(),需要 Blob 或字符串类型。我发送对象,所以我应该将其更改为 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);
  }

推荐阅读