Spring RestTemplate所需的MultipartFile参数';文件';不在场
我有一个弹簧控制器,其定义如下:Spring RestTemplate所需的MultipartFile参数';文件';不在场,spring,resttemplate,Spring,Resttemplate,我有一个弹簧控制器,其定义如下: @RequestMapping(method = RequestMethod.POST, value = "/upload") @ResponseBody public void handleFileUpload2(@RequestParam("file") MultipartFile file){ 当我使用postman时,我的请求成功。当我使用RestTemplate从另一个Spring服务发出请求时,出现以下错误: {"timestamp
@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ResponseBody
public void handleFileUpload2(@RequestParam("file") MultipartFile file){
当我使用postman时,我的请求成功。当我使用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);
}
我正在使用SpringWeb4.1.4.RELEASE
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="100000" />
</beans:bean>
确保您已将此代码添加到spring配置文件中,它可能适合您。回答此问题已晚。但我的回答可能会对寻找这个问题的人有所帮助 我遇到了一个类似的问题,改变了阅读文件的方式,为我解决了这个问题
body.add("file",new FileSystemResource(TEST_PDF_FILE_PATH));
而不是
body.add("file", new ByteArrayResource(file.getBytes()));
试一试
这对我很有用。HttpEntity requestEntity=newhttpentity(headers);交换(url、方法、requestEntity、String.class、正文);这有什么用?此XML用于配置接收端点。但是,正如我提到的,当使用Postman时,端点可以很好地工作。
body.add("file", new ByteArrayResource(file.getBytes()));
body.add("file", file.getResource());