spring-mvcresttemplate

Spring Resttemplate : how to post file and common String data at the same time


I meet a request to upload files with spring resttemplate to upload files with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?


Solution

  • You can use the following code in your application to have both multipart-file and normal request parameters at the same time:

    Note:

    String url = "http://example.com";
    String fileAbsPath = "absolute path of your file";
    String fileName = new File(fileAbsPath).getName();
    
    Files.readAllBytes(Paths.get(fileAbsPath));
    
    MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
    
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) {
        @Override
        public String getFilename() {
            return fileName;
        }
    };
    
    data.add("file", resource);
    
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("file","application/pdf");
    
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("param1", "value1")
        .queryParam("param2", "value2");
    
    HttpEntity<> entity = new HttpEntity<> (data, requestHeaders);
    
    RestTemplate restTemplate = new RestTemplate();
    
    ResponseEntity<String> result =restTemplate.exchange(
        builder.toUriString(),
        HttpMethod.POST,
        entity,
        String.class
    );
    
    System.out.println(result.getBody());