最近经常有人问 Spring Cloud Feign 如何上传文件。有团队的新成员,也有其他公司的兄弟。本文简单做个总结——
早期的 Spring Cloud 中,Feign 本身是没有上传文件的能力的(1 年之前),要想实现这一点,需要自己去编写
去实现上传。现在我们幸福了很多。因为 Feign 官方提供了子项目 feign-form ,其中实现了上传所需的
- Encoder
。
- Encoder
注:笔者测试的版本是 Edgware.RELEASE。Camden、Dalston 同样适应本文所述。
- <dependency>
- <groupId>io.github.openfeign.form</groupId>
- <artifactId>feign-form</artifactId>
- <version>3.0.3</version>
- </dependency>
- <dependency>
- <groupId>io.github.openfeign.form</groupId>
- <artifactId>feign-form-spring</artifactId>
- <version>3.0.3</version>
- </dependency>
- @FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class)
- public interface UploadFeignClient {
- @RequestMapping(value = "/upload", method = RequestMethod.POST,
- produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
- consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- @ResponseBody
- String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
- class MultipartSupportConfig {
- @Bean
- public Encoder feignFormEncoder() {
- return new SpringFormEncoder();
- }
- }
- }
如代码所示,在这个 Feign Client 中,我们引用了配置类
,在
- MultipartSupportConfig
中,我们实例化了
- MultipartSupportConfig
。这样这个 Feign Client 就能够上传啦。
- SpringFormEncoder
- @RequestMapping(value = "/upload", method = RequestMethod.POST,
- produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
- consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
不能写成
- @RequestPart(value = "file")
。
- @RequestParam(value = "file"
作者:jumping_me 周立
地址: 使用 Spring Cloud Feign 上传文件
来源: https://zhuanlan.zhihu.com/p/32047311