Content-Type in HttpClient request not changing to 'multipart/form-data'

Viewed 220

I've been trying to fix this problem for two days now, to no avail. I'm just simply trying to send an image from an input element using HttpClient. My typescript is:

  public onImageSubmit(input) {
    this.selectedFile = input.files[0];
    var uploadImageData = new FormData();
    uploadImageData.append('imageFile', this.selectedFile);

    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2R0byI6IntcInVzZXJJZFwiOjEsXCJ1c2VybmFtZVwiOlwiZ2VvcmdlXCJ9In0.pBWSj-SWVj9FuPd3r2S5MJo7AZ62mwm-MjBKj409vUYi1YuCieh1FWm0XGISHkK2cF51Tu5fzeKEwg3rr8Ya1w'
        'Content-Type': 'multipart/form-data' // I have also tried without this
      })
    }
    
    this.http.post<Image>('http://localhost:9090/users/1/images', uploadImageData, httpOptions).subscribe(response => {
        console.log(response);
    });
  }

I have a Spring web server running in the background. I get the error 'Current request is not a multipart request' on the server. Examining the request headers in Firefox shows that the Content-Type is application/json . I have tried explicitly specifiying the content type in the header, as well as leaving it out and hoping the browser will do it. Neither works. Does anyone know what I'm doing wrong?

1 Answers

Try using form-data-encoder https://github.com/octet-stream/form-data-encoder

Alternatively, have you checked your tsconfig.json compilerOptions.target? I had a similar problem with a target of es2020 which did not happen when the target was es2015. Understand that this is not an ideal solution since some dependencies may require es2020.

Related