Zuul: Uploading file through RestTemplate

Viewed 502

I try to create simple Spring Cloud model: Zuul, Eureka, MyService1, MyService2.

MyService1 & Myservice2 register by Eureka.

MyService1 configured:

@EnableAutoConfiguration
@ComponentScan
@EnableEurekaClient
@EnableJpaRepositories
@EnableFeignClients
public class ServiceOne {
    public static void main(String[] args){
        SpringApplication.run(ServiceOne.class, args);
    }
}

and has RestTemplate for uploading file into MyService2.

@Autowired
private RestTemplate restTemplate;

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.put("file", Arrays.asList(new Object[] {new ClassPathResource("testfile.txt")}));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
restTemplate.postForObject("http://service2", requestEntity, String.class);

MyService2 configured:

@SpringBootApplication
@Configuration
@ComponentScan
@EnableEurekaClient
public class ServiceTwo {
    public static void main(String[] args) {
        SpringApplication.run(ServiceTwo.class, args);
    }
}

and has RestController:

@RestController
@RequestMapping(value = AppRestController.REST_URL)
public class RootController {
@RequestMapping(value = "/context}", method = RequestMethod.POST)
    public ResponseEntity<String> upload (MultipartFile file) {
        ...

    }
}

Request recieved by

RootController

, but

file == null.

I built working simple SpringBoot application containing RestTemplate:

public class TestRestTemplate {
    public static void main(String[] args) {
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.put("file", Arrays.asList(new Object[] {new ClassPathResource("testfile.txt")}));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        //Zuul address
        restTemplate.postForObject("http://localhost:8761/service2", requestEntity, String.class);
    }
}

What do i wrong?

1 Answers

I know that it is too late to answer, in case if someone else would have a similar problem. I supouse that the problem here: map.put("file", Arrays.asList(new Object[] {new ClassPathResource("testfile.txt")})); it should looks like:

map.add("files", new ClassPathResource("testfile.txt"));

here more detail: https://www.baeldung.com/spring-rest-template-multipart-upload

Related