【问题标题】:Send Reactive Form and picture in the same request在同一个请求中发送 Reactive Form 和图片
【发布时间】:2018-10-04 13:38:47
【问题描述】:

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

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

但是:

  • 我认为我不应该这样做
  • 我认为,如果出现我不明白的错误:

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

【问题讨论】:

    标签: file post angular5 httpclient angular-reactive-forms


    【解决方案1】:

    我用来发送此请求的函数 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);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2015-02-11
      • 1970-01-01
      • 2019-12-11
      • 2021-04-25
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多