这个控制器工作正常

@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(通过邮递员)则可以工作。如果调用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"

最佳答案

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

那里的问题是关于使用RestTemplate将多部分文件发布到Rest服务。

基本上,您要做的是模拟文件上传。您可以尝试如下操作:

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);

关于java - Spring -RestTemplate-多部分文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44154252/

10-12 03:46