Feign接口实现多文件上传

本文详细介绍了如何通过Feign接口实现单文件和多文件的上传操作。在单文件上传中,服务提供者和消费者均遵循常规的Spring Boot文件上传方式。在多文件上传部分,由于Feign-form-spring库的限制,需要重写配置类以正确处理文件数组,避免覆盖问题。文章提供了重写配置类的源码和Feign接口的示例。
摘要由CSDN通过智能技术生成


前言

springBoot版本 2.1.15.RELEASE
springCloud版本 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. 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>
  1. 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);

  1. 2.2 上传文件配置单独写
    新增feign实现文件上传的配置类
@Configuration
public class FeignMultipartSupportConfig {
   
  @Bean
  public Encoder feignFormEncoder() {
   
    return new SpringFormEncoder();
  }
}

上传文件配置单独写的feign接口写法

//info是服务提供者的name
@FeignClient(value = "info/template",configuration = FeignMultipartSupportConfig
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值