Springcloud配置Feign文件上传支持

springcloud和其他框架不同的是需要跨工程的调用接口,所以在存在传递文件参数的情况下如果不进行特殊处理的话是没办法成功调用接口的。

首先需要加入对应的依赖:

        <!-- Feign进行跨服务传递文件依赖 -->
		<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 = "${feign.backmanage.name}",configuration = IProductDocService.MultipartSupportConfig.class)
public interface IProductDocService {
 
	class MultipartSupportConfig {
		@Bean
		public Encoder feignFormEncoder() {
			return new SpringFormEncoder();
		}
	}
 
}

果然事情并没有那么顺利,出现了这个异常

feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type

按照异常信息来看,对于请求没有找到合适的HttpMessageConverter,奇怪了,我不适合使用了@bean实例化了吗

仔细一看,原来并没有向spring声明这是个配置类啊,所以正确的应该是这样的,快来找不同,:

@FeignClient(name = "${feign.backmanage.name}",configuration = IProductDocService.MultipartSupportConfig.class)
public interface IProductDocService {
    @Scope("prototype")
    @Primary
    @Configuration
	class MultipartSupportConfig {
        @Autowired
		private ObjectFactory<HttpMessageConverters> messageConverters;
		@Bean
		public Encoder feignFormEncoder() {
			return new SpringFormEncoder(new SpringEncoder(messageConverters));
		}
	}
 
}

配置工作到这里就完成了,接下来在书写接口的时候要注意了,你可以参照着这样子来写

@RequestMapping(value = "/test",method = RequestMethod.POST,produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	String test(@RequestPart(value = "file", required = false) MultipartFile file,@RequestParam(value = "name") String name);

其中【consumes = MediaType.MULTIPART_FORM_DATA_VALUE】是必须的,否则人家怎么知道你传的是文件呢

第二个是对于文件你不能使用@RequestParam了,要使用@RequestPart,不然就会报这个异常:

Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

然后就可以啦

原文:https://blog.csdn.net/hlp4207/article/details/81235487

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值