3

我尝试创建简单的 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);
    }
}

并具有用于将文件上传到 MyService2 的 RestTemplate。

@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) {
        ...

    }
}

收到的请求

根控制器

, 但

文件 == 空。

我构建了包含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);
    }
}

我错了什么?

4

1 回答 1

0

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

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

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

于 2020-10-31T12:21:08.500 回答