无法通过RestTemplate
问题描述:
将文件上传到春天REST服务
我写了接受多文件作为参数小弹簧控制器无法通过RestTemplate
@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")
+1
它没有它的工作 –
你可以得到更全面的信息看服务器控制台。我认为'@ RequestPart'在这里更合适,而不是'@ RequestParam',因为它是一个文件。 – Vasan
@Vasan没有'@ RequestParam'的作品 –