Spring - RestTemplate - Multipart File

时间:2017-05-24 09:23:46

标签: java spring spring-mvc multipart

此控制器工作正常

@Controller
public class FileUploadController {
....
@PostMapping("/convert")
public void fileUpload(@RequestParam("file") MultipartFile file, 
     RedirectAttributes redirectAttributes, HttpServletResponse response) {

现在我想通过RestTemplate从另一个spring项目调用这个控制器。我尝试了很多东西,但注意到了。这是我的最后一段代码:

@Controller
public class FileController {
....
@PostMapping("/convert")
public void fileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes,
        HttpServletResponse response) throws Exception {


    ArrayList<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(
            Arrays.asList(new FormHttpMessageConverter(),new MappingJackson2HttpMessageConverter(), new ResourceHttpMessageConverter()));

    RestTemplate template = restTemplate();

    template.setMessageConverters(converters);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
    multipartRequest.add("file", file);

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, header);

    template.postForObject("http://localhost:8080/convert", requestEntity, String.class);

}

我如果调用FileUploadController(通过postman),它的工作原理。如果调用FileController 我得到了这个例外

"exception": 
"org.springframework.http.converter.HttpMessageNotWritableException",
"message": "Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile]",
"path": "/convert"

1 个答案:

答案 0 :(得分:2)

看看这里的答案,它应该正是您所寻找的:Attempting to test rest service with multipart file

问题在于使用RestTemplate将多部分文件发布到休息服务。

基本上,您需要做的是模拟文件上传。你可以尝试这样的事情:

MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("file", new FileSystemResource("file.jpg"));

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "multipart/form-data");
headers.set("Accept", "text/plain");

String result = restTemplate.postForObject(
    "http://host:port/path", 
    new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), 
    String.class);