Spring’s RestTemplate

Spring’s RestTemplate

/**
 * After the word document is generated in memory we can upload it to the server.
 *
 * @param fileContents The byte array we're wanting to POST
 * @param filename     The name of the file you're uploading. You can make yours up if you want.
 */
private static void uploadWordDocument(byte[] fileContents, final String filename) {
    RestTemplate restTemplate = new RestTemplate();
    String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; // Dummy URL.
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();

    map.add("name", filename);
    map.add("filename", filename);

    // Here we 
    ByteArrayResource contentsAsResource = new ByteArrayResource(fileContents) {
        @Override
        public String getFilename() {
            return filename; // Filename has to be returned in order to be able to post.
        }
    };

    map.add("file", contentsAsResource);

    // Now you can send your file along.
    String result = restTemplate.postForObject(fooResourceUrl, map, String.class);
    
    // Proceed as normal with your results.
}

 

Guess you like

Origin www.cnblogs.com/stono/p/10942062.html