Feign接口实现多文件上传
前言
springBoot版本 2.1.15.RELEASEspringCloud版本 Greenwich.SR6
springCloud 的Feign组件并不支持文件的传输,所以Feign接口文件传输需要在Feign接口中增加依赖。
一、Feign接口实现单文件上传
1.服务提供者(被Feign调用的)
和平常的springboot文件上传接口一样
@RestController
@RequestMapping("/template")
public class FileController {
@Resource
private FileService fileService;
/**
* 增加单个文件
* @param tag 文件标识
* @param file 要上传的文件
* @return 文件上传的结果
*/
@RequestMapping(value="/addFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE,produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE})
public Result addFile(@RequestParam("tag") String tag, @RequestPart MultipartFile file){
//文件上传处理
return fileService.addTemplate(tag,file);
}
2.服务消费者
- 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>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- 2 feign接口
2.2.1 上传文件配置写在接口内
//info是服务提供者的name
@FeignClient(value = "info/template",configuration = FileClient.MyConfig.class)
public interface FileClient {
/**
* 支持文件上传配置
* 此配置也可以单独写,见下面2.2.2的写法
*/
class MyConfig {
@Bean
public SpringFormEncoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
/**
* 增加单个文件
* @param tag 文件标识
* @param file 要上传的文件
* @return 文件上传的结果
*/
@RequestMapping(value="/addFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE})
Result addFile(@RequestParam("tag") String tag, @RequestPart MultipartFile file);
- 2.2 上传文件配置单独写
新增feign实现文件上传的配置类
@Configuration
public class FeignMultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
上传文件配置单独写的feign接口写法
//info是服务提供者的name
@FeignClient(value = "info/template",configuration = FeignMultipartSupportConfig