如何通过 RestTemplate Client 和 Server 上传图片到 Server()

How Upload image to Server() via RestTemplate Client and Server

我正在使用 RestTemplate 客户端代码并希望在服务器端访问图像。我想在 Tomcat 的自定义目录中上传图片,但出现错误:

Caused by: org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.apache.http.entity.mime.MultipartEntity] and content type [multipart/form-data]

RestTemplate 客户端代码:

public String saveCompanylogo(File file){
        String url = COMPANY_URL+ "/saveCompanyLogo";
        MultipartEntity multiPartEntity = new MultipartEntity ();
        FileBody fileBody = new FileBody(file) ;
        //Prepare payload
        multiPartEntity.addPart("file", fileBody) ;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultipartEntity> entity = new HttpEntity<MultipartEntity>    (multiPartEntity, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url,     HttpMethod.POST, entity,  new ParameterizedTypeReference<String>() {
        });
        return exchange.getBody();
    }

我的服务器端(控制器)代码是:

@RequestMapping(method = POST, value = "/saveCompanyLogo")
    @Consumes("multipart/form-data")
    public String saveCompanylogo(@RequestParam("file") MultipartFile file)         {
      System.out.println(""+file);   
     //Todo coding
     return "stringData";
    }

我使用 FileSystemResource 而不是 FileBody。这是我的代码:

restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());

Map params = new LinkedMultiValueMap();
params.put("file", new FileSystemResource(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

在服务器端(我使用 Jersey 而不是 MVC,但我想没关系):

@RequestMapping(method = POST, value = "/saveCompanyLogo")
@Consumes("multipart/form-data")
public String saveCompanylogo(@RequestParam("file") InputStream file) {
    //DO SOMETHING
}

希望对您有所帮助