Maria Gálvez
Maria Gálvez

Reputation: 307

Required request part 'file' is not present] springboot client

i have this code in client:

          RestTemplate restTemplate = new RestTemplate();
          File file = new File("C:\\temp\\aadocejem.doc");
          MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();

          map.add("file", file);


          String result = restTemplate.postForObject(url+"/doc_file", map, String.class);

And this code is what you call the above:

 @PostMapping("/doc_file")
    public ResponseEntity<File> docFileV1(
        @RequestParam("file") MultipartFile originalDocFile) {

        return ResponseEntity.ok(docFileService.processDocFile(originalDocFile));

    }

The error it gives me on the server: Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

The error it gives me in the client: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{"timestamp":"2020-04-23T10:55:32.258+0000","status":400,"error":"Bad Request","message":"Required request part 'file' is not present","trace":"org.springframework.web.multipart.support.MissingServlet... (5758 bytes)]

Upvotes: 1

Views: 2361

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36103

This will not work with postForObject.

Use postForEntity instead:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART__FORM__DATA);

MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(file));

HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(url+"/doc_file", requestEntity, String.class);

Upvotes: 4

Related Questions