0

Suppose I have a front end. On said front end, I want to upload a file. The controller in the Spring Boot (Java) app receives said file as a MultipartFile (Service A). I want to take the input stream from that, and send it to a different service (Service B) without writing said stream to the file system. Service B should return something to Service A which sends said response to the client to let me know it has handled said file after completion of the streaming. I am unsure which libraries/classes to use to achieve this in a Spring Boot app. I assume Java or Spring Boot has all kinds of helper classes to make this trivial, I'm just unsure which and how to string them together in the correct order.

Client --> Service A --> Service B

Any help would be appreciated, as the current approach of writing it to a file system is a horrible approach that I want refactored ASAP.

@Autowired
RestTemplate restTemplate

public customResponse myFileUpload(@RequestParam("foo") MultipartFile myFile) {
  //myFile comes in fine, I can pull input stream via myFile.getInputStream();
  //Should pull stream from myFile and return response from Service A here.
  //Not sure if I need to map the input to an outputStream or something?

  return restTemplate.postForObject(serviceA.url, ???, customResponse.class);
}
Paul
  • 276
  • 1
  • 8
  • 1
    https://stackoverflow.com/questions/59634993/how-to-pass-multipart-file-from-one-service-to-another-service-in-spring-boot – PeterMmm Apr 04 '22 at 17:34
  • @PeterMmm I appreciate the feedback! I do not use Feign Client, though. Their solution requires it. – Paul Apr 04 '22 at 17:53

1 Answers1

1

Using RestTemplate you can send Multipart Form Data requests. Below you can find a code snippet on how to prepare such requests. Also RestTemplate allows you to upload Resource, which you can obtain from the MultipartFile by calling MultipartFile#getResource()

public String myFileUpload(@RequestParam("foo") MultipartFile myFile) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("bar", myFile.getResource());

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

    ResponseEntity<String> responseEntity = restTemplate.postForEntity(
        "http://localhost:8080/serviceB", // <-- put real endpoint here
        requestEntity,
        String.class
    );

    return responseEntity.getBody();
}
jumb0jet
  • 863
  • 6
  • 21
  • Hello. myFile.getResource() literally gives you the .tmp file location on file system. Is this solution safe? edit: the file on myFile.getResource().multipartFile.part.location is contains the file I am uploading. – Tomáš Johan Prítrský Aug 16 '23 at 19:52