Search code examples
javaspring-mvcresttemplate

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


I am using RestTemplate Client Code and Want to access Image on Server side. I want to upload image on custom Directory of Tomcat, i am getting error:

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 Client Code:

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

My Server side(Controller) code is :

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

Solution

  • I use FileSystemResource instead of FileBody. This is my code:

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

    And in server side (I use Jersey instead of MVC, but I guess no matters):

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

    Hope it helps