Zuul:通过RestTemplate上传文件

时间:2016-03-09 15:44:56

标签: java netflix-zuul spring-cloud-netflix

我尝试创建简单的Spring Cloud模型:Zuul,Eureka,MyService1,MyService2。

MyService1& Myservice2由Eureka注册。

MyService1已配置:

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

并使用RestTemplate将文件上传到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已配置:

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

并且有RestController:

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

    }
}

收到的请求
  

RootController

,但是

  

file == null。

我构建了包含RestTemplate的工作简单SpringBoot应用程序:

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);
    }
}

我错了什么?

1 个答案:

答案 0 :(得分:0)

我知道现在回答还为时已晚,以防其他人遇到类似问题。 我想这里的问题: map.put(“ file”,Arrays.asList(new Object [] {new ClassPathResource(“ testfile.txt”)})));; 它应该像这样:

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

这里有更多详细信息: https://www.baeldung.com/spring-rest-template-multipart-upload