我具有被這樣定義一個Spring控制器:RestTemplate需要MultipartFile參數「文件」是不存在
@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ResponseBody
public void handleFileUpload2(@RequestParam("file") MultipartFile file){
當我使用郵遞員,我的請求成功。當我使用RestTemplate使用另一個春天服務的請求,我得到以下錯誤:
{"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); – Veeram