0

I want to forward a list of Multipart File from service1 to service2. It looks like below: Client -> Service1 -> Service2

In Service1: I use Executor Service to send the files

@RestController
@RequestMapping("service1")
public class TestController {

    @PostMapping(value = "upload", produces = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<Void> upload(@RequestPart MultipartFile file) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(() -> {
            sendFile(file);
        });
        return ResponseEntity.ok().build();
    }

    private void sendFile(MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "multipart/form-data");

        MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
        parameters.add("file", file.getResource());

        HttpEntity requestEntity = new HttpEntity<>(parameters, headers);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.exchange("http://localhost:8081/service2/upload",  HttpMethod.POST,  requestEntity, String.class);
    }
}

In Service2:

@RestController
@RequestMapping("service2")
public class TestController {
    Logger logger = LoggerFactory.getLogger(TestController.class);

    @PostMapping(value = "upload", produces = {MediaType.MULTIPART_FORM_DATA_VALUE}, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<Void> upload(@RequestPart MultipartFile file) {
        try {
            logger.info("fileName: {}", file.getOriginalFilename());
            logger.info("fileBytes: {}", file.getBytes());
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

The Output:

2022-11-23 11:14:40.277  INFO 26324 --- [nio-8081-exec-4] c.b.b.controller.TestController          : fileName: testFile.txt
2022-11-23 11:14:40.277  INFO 26324 --- [nio-8081-exec-4] c.b.b.controller.TestController          : fileBytes: []

The problem is in Service2 I got the file with 0 bytes (I got the fileName but not bytes).

If I remove the executorService and run "sendFile()" normally then it works.

I would like to know the reason and some solutions for this.

Thank you

  • web stuff is thread based, you are passing things on to a new thread that doesn't see the data. Request is completed, temp files are cleaned up hence no more data. – M. Deinum Nov 22 '22 at 09:10
  • Please provide enough code so others can better understand or reproduce the problem. – Community Nov 22 '22 at 10:19

0 Answers0