Close

Spring - RestTemplate File Upload Example

[Updated: Dec 13, 2017, Created: Dec 13, 2017]

Following example shows how to upload a file by using RestTemplate.

Example

A Spring Restful Controller to handle file upload

@RestController
@RequestMapping("/upload")
public class FileUploadController {

  @RequestMapping(method = RequestMethod.POST)
  public String handleFileUpload(
          @RequestParam("user-file") MultipartFile multipartFile) throws IOException {
      String name = multipartFile.getOriginalFilename();
      System.out.println("File name: "+name);
      //todo save to a file via multipartFile.getInputStream()
      byte[] bytes = multipartFile.getBytes();
      System.out.println("File uploaded content:\n" + new String(bytes));
      return "file uploaded";
  }
}

See also Spring MVC file upload tutorial.

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

RestTemplate uploading a File

public class UploadClient {

  public static void main(String[] args) throws IOException {
      MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
      bodyMap.add("user-file", getUserFileResource());
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);

      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/upload",
              HttpMethod.POST, requestEntity, String.class);
      System.out.println("response status: " + response.getStatusCode());
      System.out.println("response body: " + response.getBody());
  }

  public static Resource getUserFileResource() throws IOException {
      //todo replace tempFile with a real file
      Path tempFile = Files.createTempFile("upload-test-file", ".txt");
      Files.write(tempFile, "some test content...\nline1\nline2".getBytes());
      System.out.println("uploading: " + tempFile);
      File file = tempFile.toFile();
      //to upload in-memory bytes use ByteArrayResource instead
      return new FileSystemResource(file);
  }
}
uploading: C:\Users\Joe\AppData\Local\Temp\upload-test-file1051379468467597241.txt
response status: 200
response body: file uploaded

Output on the server:

File name: upload-test-file4223155062528304169.txt
File uploaded content:
some test content...
line1
line2

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • commons-fileupload 1.3.2: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications.
  • JDK 1.8
  • Maven 3.3.9

Spring RestTemplate FileUpload example Select All Download
  • rest-template-upload-file-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • client
                  • UploadClient.java
                  • server

    See Also