1. 原因
默认情况下,在SpringCloud Alibaba 微服务项目中,无法通过消费者服务直接将前端上传的文件,以请求的方式发送到服务提供者来操作文件上传的。
因此需要在 OpenFeign 中将 文件名称 和 文件内容的Base64 封装为类,消费者添加 consumes 文件上传参数。
2. 解决
2.1 依赖
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.8.0</version> </dependency>
|
2.2 参数
消费者 OssService 接口(@FeignClient
注解修饰不需要实现类),
添加参数 consumes = MediaType.MULTIPART_FORM_DATA_VALUE
1 2 3 4 5 6 7 8 9 10 11 12 13
| import org.springframework.http.MediaType;
@FeignClient("jerryProvider") public interface OssService {
@PostMapping(value = "provider/oss/upload.do", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) R upload(MultipartFile file); }
|
消费者控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @RestController @RequestMapping("/api/oss/") public class OssController { @Autowired private OssService service;
@PostMapping("upload.do") public R upload(@RequestPart MultipartFile file) { return service.upload(file); } }
|
提供者控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @RestController @RequestMapping("/provider/oss/") public class OssController { @Autowired private OssService service;
@PostMapping("upload.do") public R upload(MultipartFile file) { return service.upload(file); } }
|
2.3 Feign 配置类
消费者中的配置类:实现Feign对表单传输文件的支持
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration public class FeignMultipartSupportConfig { @Autowired private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean public Encoder multipartFormEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); }
@Bean public feign.Logger.Level multipartLoggerLevel() { return feign.Logger.Level.FULL; } }
|
2.4 Feign配置超时时间
application.yml
1 2 3 4 5 6
| feign: client: config: default: connectTimeout: 10000 readTimeout: 20000
|