'File upload Angular 13 Spring boot rest Required request part 'file' is not present

I'm searching since days now for a solution and can not find any. I have a simple Spring Boot Rest application (Spring version 2.6.7) with an endpoint to upload a file:

@PostMapping(path = "/upload")
public ResponseEntity<UploadResponseDto> upload(@Valid @NotNull @RequestParam("file") MultipartFile file){

    UploadResponseDto responseDto = uploadSerice.processDocument(file);

    return ResponseEntity.ok(responseDto);
}

If I send a file with Insomnia or Postman it works out of the box. The body content of the request in Insomnia looks like this:

POST /upload HTTP/1.1
Host: localhost:8081
User-Agent: insomnia/2021.7.2
Content-Type: multipart/form-data; boundary=X-INSOMNIA-BOUNDARY
Accept: */*
Content-Length: 40526

--X-INSOMNIA-BOUNDARY
Content-Disposition: form-data; name="file"; filename="test.pdf"
Content-Type: application/pdf
%PDF-1.6
...

If i do the same request with my Angular application I get always the following error:

Could not resolve parameter [0] in public org.springframework.http.ResponseEntity<[...].UploadResponseDto> [...].UploadController.upload(org.springframework.web.multipart.MultipartFile): Required request part 'file' is not present

The Angular function for uploading:

export class FileService {
  private baseUrl = 'http://localhost:8081';

  constructor(private http: HttpClient) { }

  upload(file: File): Observable<UploadResponse> {
    const formData: FormData = new FormData();

    formData.set('file', file);
    return this.http.post<UploadResponse>(`${this.baseUrl}/upload`, formData);
  }

}

The call of the upload service with an ngxs action:

  @Action(UploadFile)
  saveStudyInfo(ctx: StateContext<UploadStateModel>, file: File): void {
    this.fileService.upload(file).subscribe((uploadResponse) => {
      ctx.patchState({
        uploadResponse: uploadResponse
      });
    });
  }

The request headers in Firefox:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US
Connection: keep-alive
Content-Length: 176
Content-Type: multipart/form-data; boundary=---------------------------232165386063793317893093
Host: localhost:8081
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0

The request body:

-----------------------------232165386063793317893093
Content-Disposition: form-data; name="file"

[object Object]
-----------------------------232165386063793317893093--

The file is there but I can not figure out what is wrong. This driving me nuts... Do I overlook something???

Hope someone can help. Thanks in advance :)

Best Martin



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source