多部分文件(多个文件)使用Spring Rest Template + Spring Web MVC上传

时间:2016-10-13 13:05:47

标签: java spring rest spring-mvc

我无法使用Rest模板发送多个文件。如何在单个REST模板调用和接收器(主机)端发送多个文件什么是控制器方法?

以下代码代码用于发送单个文件。

客户端代码

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = 
    new HttpEntity<LinkedMultiValueMap<String, Object>>(map, headers);

ResponseEntity<String> result = template.get().exchange(
    contextPath.get() + path, HttpMethod.POST, requestEntity,
    String.class);

主机控制器代码

@RequestMapping("/url")
@ResponseBody
public String readFiles( MultipartFile file){
    ---
    ---
}

1 个答案:

答案 0 :(得分:0)

 FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        formHttpMessageConverter.setCharset(Charset.forName("UTF8"));

        RestTemplate restTemplate = new RestTemplate();

        restTemplate.getMessageConverters().add(formHttpMessageConverter);
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        restTemplate.setInterceptors(Arrays.asList(new LoggingRequestInterceptor()));

        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        String uri = "https://if-one.pl/api/v1/documents";

        String imagePath = "/path_to_file/do1.jpg";
        String imagePath2 = "/path_to_file/do2.jpg";

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("doctype", "idcard");

        Resource file1 = new FileSystemResource(imagePath);
        Resource file2 = new FileSystemResource(imagePath2);

        map.add("file", file1);
        map.add("file", file1);
        HttpHeaders imageHeaders = createHeaders();
        imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);

        HttpEntity<String> request = new HttpEntity<String>(imageHeaders);
        ResponseEntity<String> resposne =
                restTemplate.exchange(uri, HttpMethod.POST, imageEntity, String.class);