spring-bootspring-mvcuploadrest-clientmultipartfile

How to transmit Multipart file object into Spring web RestClient post method


I have two microservices:

Process :

@PostMapping(value ="/create")
 ResponseEntity<Response> createVideo(@RequestParam("file") MultipartFile multipartFile) 
 {  
    videoRestClientService.upload(multipartFile);
    return new ResponseEntity<Response>(new Response("video has been stored"), HttpStatus.OK);
 }
public Response upload(MultipartFile multipartFile){
    
    RestClient restClient = RestClient.create("http://localhost:8095");
    Response response = restClient.post()
     .uri("/uploadfile")
     .contentType(...)
     .body(multipartFile)
     .retrieve()
     .body(Response.class);
}

-> In videoStore microService

@PostMapping("/uploadfile") 
public ResponseEntity<Response> uploadFile(@RequestParam("file") MultipartFile multipartFile) {

    Response response = fileSystemStorage.storeFile(multipartFile);

    return new ResponseEntity<Response>(response, HttpStatus.OK);
}
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.1.2</version>
</dependency>

Question :

Remark :


Solution

  • Is it possible to use restClient to post multipartFile ?

    I don't know if you have solved this yet. But the answer is yes. I was doing the same thing and have just made it works after a day of researching. Here is what you need:

    import org.springframework.web.client.RestClient;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.core.io.Resource;
    import org.springframework.http.MediaType;
    
     
    public Response upload (MultipartFile multipartFile) {
        // I am not create RestClient like this. I use @Autowired instead
        RestClient restClient = RestClient.create("http://localhost:8095");
        MultiValueMap<String, Resource> body = new LinkedMultiValueMap<>();
        body.add("file", multipartFile.getResource());
        Response response = restClient.post()
                .uri("/uploadfile")
    //            .contentType(MediaType.MULTIPART_FORM_DATA)  // Not need
                .body(body)
                .retrieve()
                .body(Response.class);
        return response;
    }