DEBENDRA DHINDA
DEBENDRA DHINDA

Reputation: 1193

Upload MultipartFiles using RestTemplate

I have two end-points. One endpoint will receive files from Postman and should foreward the same files to another endpoint using RestTemplate.

The 2nd endpoint is getting invoked, but no files.

endpoint 1:

@PostMapping("/upload/test")
    public String testUpload(@RequestParam("files") List<MultipartFile> files) throws IOException{

        if (files.isEmpty()) {          
            return "Please select a file . . .";
        }
        System.out.println("**** Number of files : "+files.size());



        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        List<Object> f = new ArrayList<>();
        for(MultipartFile file : files) {
            f.add(new ByteArrayResource(file.getBytes()));
        }
        map.put("files", f);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

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


        return "success";
    }

Endpoint 2:

@PostMapping("/upload/test/client")
    public String testClient(@RequestParam("files") List<MultipartFile> files){
        System.out.println("********inside client  *****************");
        System.out.println(files);
        return "200";
    }

O/P :

**** Number of files : 2
********inside client  *****************
[]
response status: 200 OK
response body: 200

Upvotes: 1

Views: 1094

Answers (2)

DEBENDRA DHINDA
DEBENDRA DHINDA

Reputation: 1193

I resolved the questions as follows and is working for multiple files too .

Endpoint 1

    @PostMapping("/upload")
    public ResponseEntity testUpload(@RequestParam("file") List<MultipartFile> file) throws IOException{
        System.out.println("********received file:"+file.size());
        String serverUrl = "http://localhost:8080/upload/client";

        MultiValueMap<String, Object> body =getMultivalueMap(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity= new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
        System.out.println(response);

        return new ResponseEntity<>(HttpStatus.OK);
    }

Endpoint 2

   @PostMapping("/upload/client")
    public ResponseEntity testClient(@RequestParam("file") List<MultipartFile> file){

        System.out.println("********client file:"+file.size());
        file.forEach(f->{
            System.out.println("### Client File Name :"+f.getOriginalFilename());           
        });
        return new ResponseEntity<>(HttpStatus.OK);
    }

Body content

private MultiValueMap<String, Object> getMultivalueMap(List<MultipartFile> files) throws IOException {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        for(MultipartFile file : files) {
            ByteArrayResource contentsAsResource = new ByteArrayResource(file.getBytes()){
                @Override
                public String getFilename(){
                    return file.getOriginalFilename();
                }
            };
            map.add("file", contentsAsResource);
        }
        return map;
    }

Upvotes: 3

varman
varman

Reputation: 8894

From the knowledge, you can create a temporary file using File f=File.createTempFile() and delete it after successful transaction using f.deleteOnExit().

File tempFile = null;
try {
    String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename()); // from apachi common io
    tempFile = File.createTempFile("temp", extension); // can pass the directory also as a third parameter
    file.transferTo(tempFile);
} catch (IOException e) {
    e.printStackTrace();
}

I haven't tried to forward a file to another endpoint, but successfully done for strings. Hopefully, the above method must help to overcome the problem. For more info of file Java doc

Upvotes: -1

Related Questions