使用Spring Cloud Feign上传文件
2017-12-04 00:00
483 查看
原文:http://http://www.itmuch.com/spring-cloud-sum/spring-cloud-feign-upload/
采用 CC BY 3.0 CN 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。
最近经常有人问Spring Cloud Feign如何上传文件。有团队的新成员,也有其他公司的兄弟。本文简单做个总结——
早期的Spring Cloud中,Feign本身是没有上传文件的能力的(1年之前),要想实现这一点,需要自己去编写
注:笔者测试的版本是Edgware.RELEASE。Camden、Dalston同样适应本文所述。
如代码所示,在这个Feign Client中,我们引用了配置类
中的
接口定义中的注解
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
采用 CC BY 3.0 CN 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。
最近经常有人问Spring Cloud Feign如何上传文件。有团队的新成员,也有其他公司的兄弟。本文简单做个总结——
早期的Spring Cloud中,Feign本身是没有上传文件的能力的(1年之前),要想实现这一点,需要自己去编写
Encoder去实现上传。现在我们幸福了很多。因为Feign官方提供了子项目feign-form ,其中实现了上传所需的
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>
编写Feign Client
@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中,我们实例化了
SpringFormEncoder。这样这个Feign Client就能够上传啦。
注意点
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
中的
produeces、
consumes不能少;
接口定义中的注解
@RequestPart(value = "file")不能写成
@RequestParam(value = "file"。
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
相关文章推荐
- 使用Spring Cloud Feign上传文件的示例
- Spring Cloud中FeignClient支持上传文件的同时提交表单数据
- Spring Cloud Feign Client 实现MultipartFile上传文件功能
- spring cloud feign 上传文件报not a type supported by this encoder解决方案
- Spring Cloud Feign Client 实现MultipartFile上传文件功能
- Spring Cloud中FeignClient添加上传文件功能
- Spring Cloud Feign的文件上传实现的示例代码
- spring cloud feign 上传文件
- spring cloud feign 多文件上传实现
- 第二十三章 使用Spring cloud+zuul使用API网关进行上传文件
- Spring Cloud Feign(1.5.9) 进行文件上传
- spring cloud-Feign使用中遇到的问题总结
- 【uploadify】使用Uploadify+SpringMVC实现不用From文件页面无刷上传
- 使用Spring CommonsMultipartResolver 上传文件
- spring-mvc使用ajaxFileUpload上传文件总是进入error方法
- 在spring boot中使用restTemplate上传大文件Java heap space
- 文件上传(Springcloud与mongo集合)
- Spring Cloud(Netflix) Feign: 以Dubbo暴露服务的方式使用Feign
- 使用spring-mvc实现文件上传
- 使用Spring Cloud Feign作为HTTP客户端调用远程HTTP服务