场景:
上传图片的服务为A,然后B服务通过feign
客户端调用A服务并传递 MultipartFile
步骤1:加入依赖
<!-- Feign进行跨服务传递文件依赖 -->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.8.0</version>
</dependency>
步骤2:添加配置 FeignConfiguration
@Configuration
public class FeignConfiguration implements RequestInterceptor {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
// new一个form编码器,实现支持form表单提交
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
步骤3:Feign
客户端调整
@PostMapping(value = "/fileupload",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String fileUpload(@RequestPart(value = "file") MultipartFile file, @RequestParam String path);
注意:不能使用 @RequestParam (value = "file")
,使用 @RequestPart(value = "file")
常见的异常
feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type
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