先说一下调用流程:
页面请求 -> 服务A中的controller -> 服务A的feign Interface -> 服务B的controller
springcloud和其他框架不同的是需要跨模块地调用接口,所以如果在传递文件参数的时候不进行特殊处理的话是没办法成功调用接口的。
首先处理服务A:
需要加入对应的依赖(如果springboot版本高于2.0,feign-form-spring的版本最好不低于3.5):
<!-- 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>
然后你需要在feign接口中引入一个配置类
@FeignClient(name = "${feign.xxx.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));
}
}
}
其次,在服务A中的配置文件配置如下内容:
multipart.enabled=true
multipart.file-size-threshold=0
# 最大支持文件大小
multipart.maxFileSize=10MB
multipart.maxRequestSize=10MB
配置工作到这里就完成了,接下来在书写feign接口的时候要注意了,你可以参照着这样子来写
@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
再处理服务B:
服务B的controller:

配置文件:
spring.http.multipart.enabled=true
spring.http.multipart.file-size-threshold=0
# 最大支持文件大小
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
然后~大功告成~