[英]Unable to upload a file to Spring REST service via RestTemplate
我写了一个小的Spring控制器,它接受多部分文件作为参数
@PutMapping("/fileUpload")
public String test(@RequestParam("test") MultipartFile file) {
System.out.println("In controller");
return file.getOriginalFilename();
}
我正在使用的相应RestTemplate是
Path path = Paths.get("C:\\Users\\Foo\\Desktop", "baz.txt");
FormHttpMessageConverter messageConverter = new FormHttpMessageConverter();
messageConverter.addPartConverter(new ByteArrayHttpMessageConverter());
RestTemplate client = new RestTemplate();
client.getMessageConverters().add(messageConverter);
String end_url = "http://localhost:8888/test/fileUpload";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
body.add("test", new ByteArrayResource(Files.readAllBytes(path)));
HttpEntity<MultiValueMap<String, Object>> entity
= new HttpEntity<MultiValueMap<String, Object>>(body, headers);
client.exchange(end_url, HttpMethod.PUT, entity, String.class, new HashMap());
无论我尝试什么,都会不断收到以下错误:
Caused by: org.springframework.web.client.HttpClientErrorException: 400 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:540) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.controller.Runner.run(Runner.java:57) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
... 6 common frames omitted
我究竟做错了什么 ? 我尝试添加所有典型的消息转换器,例如ByteArrayHttpMessageConverter,ResourceHttpMessageConverter,并且还尝试使用commons-fileupload
谁能告诉我我的RestTemplate做错了什么?
你好吗? 尝试修改您的
@PutMapping("/fileUpload")
至
@PutMapping(value = "/fileUpload", consumes = "multipart/form-data")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.