Send Reactive Form and picture in the same request

I have Reactive Form with some of fields:

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

In the onSubmit method I assign fields from the form to class Point:

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

But I don't know, how to send in the same request both form data and image.

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

I did something like that:

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

But:

Error

What is the correct way to send this type of reqests?

Upvotes: 0

Views: 36

Answers (1)

Function append(), which I use to send this request, required type Blob or string. I send object, so I should change it to JSON string. Now it works correctly.

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

Upvotes: 1

Related Questions