【问题标题】:Zuul: Uploading file through RestTemplateZuul:通过 RestTemplate 上传文件
【发布时间】:2016-03-09 15:44:55
【问题描述】:

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

    }
}

请求由

收到

根控制器

,但是

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

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    我知道现在回答为时已晚,以防其他人遇到类似问题。 我认为这里的问题是: 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2020-03-18
      • 2021-09-18
      • 1970-01-01
      • 2020-04-12
      • 2014-05-19
      • 1970-01-01
      相关资源
      最近更新 更多