项目场景:
服务B 要通过 Feign 上传文件到服务A
问题描述:
这里使用FeignClient通过MultipartFile来上传文件,报了以下错误:
class XXX is not a type supported by this encoder.
原因分析:
OpenFeign 默认不支持文件参数 MultipartFile 。
解决方案:
OpenFeign提供了可扩展工具,只需要以下两个步骤即可。
(1)添加配置类 FeignMultipartSupportConfig
import feign.codec.Encoder;import feign.form.spring.SpringFormEncoder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Primary;import org.springframework.context.annotation.Scope;publicclassFeignMultipartSupportConfig{@Bean@Primary@Scope("prototype")public EncodermultipartFormEncoder(){returnnewSpringFormEncoder();}@Beanpublic feign.Logger.LevelmultipartLoggerLevel(){return feign.Logger.Level.FULL;}}
(2)修改 Feign 类,增加 configuration 加载和 consumes 属性
import org.springframework.cloud.openfeign.FeignClient;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestPart;import org.springframework.web.multipart.MultipartFile;@FeignClient(name="FileFeign", url="${epl.sync.service.url}", path="/alone-server", configuration= FeignMultipartSupportConfig.class)publicinterfaceFileFeign{/**
* 文件上传
*
* @param file 文件
* @return 文件id
*/@PostMapping(value="/upload", consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
Result<String>upload(@RequestPart("file") MultipartFile file);}