【发布时间】:2017-02-12 13:13:57
【问题描述】:
我有一个这样定义的 Spring 控制器:
@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ResponseBody
public void handleFileUpload2(@RequestParam("file") MultipartFile file){
当我使用邮递员时,我的请求成功。当我使用 RestTemplate 从另一个 Spring 服务发出请求时,我收到以下错误:
{"timestamp":1475579425804,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'file' is not present","path":"/upload"}
这是我使用 RestTemplate 发出请求的方式。
public void uploadFile(MultipartFile file, String url) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new ByteArrayResource(file.getBytes()));
RestTemplate restTemplate = new RestTemplate();
HttpEntity requestEntity = new HttpEntity(body, headers);
restTemplate.exchange(url, method, requestEntity, String.class);
}
我无法弄清楚我在这里做错了什么。 This 问题似乎表明您需要添加一些 xml 以使其正常工作,但由于它可以从 Postman 工作,我相信实际问题与我如何使用 RestTemplate 进行其余调用有关。
如果我打印出requestEntity,我会得到以下信息:
<{file=[resource loaded from byte array]},{Content-Type=[multipart/form-data]}>
我正在使用spring-web 4.1.4.RELEASE
【问题讨论】:
-
HttpEntity requestEntity = new HttpEntity(headers); restTemplate.exchange(url, method, requestEntity, String.class, body);
标签: spring resttemplate