所需的请求部分 'file' 不存在] springboot 客户端
Required request part 'file' is not present] springboot 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);
这段代码就是你上面所说的:
@PostMapping("/doc_file")
public ResponseEntity<File> docFileV1(
@RequestParam("file") MultipartFile originalDocFile) {
return ResponseEntity.ok(docFileService.processDocFile(originalDocFile));
}
它在服务器上给我的错误:已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分 'file' 不存在]
它在客户端给我的错误: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字节)]
这不适用于 postForObject。
改为使用 postForEntity:
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);
我在客户端有这个代码:
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);
这段代码就是你上面所说的:
@PostMapping("/doc_file")
public ResponseEntity<File> docFileV1(
@RequestParam("file") MultipartFile originalDocFile) {
return ResponseEntity.ok(docFileService.processDocFile(originalDocFile));
}
它在服务器上给我的错误:已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分 'file' 不存在]
它在客户端给我的错误: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字节)]
这不适用于 postForObject。
改为使用 postForEntity:
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);