feign接口上传多个文件


前言

原生的spring-feign接口只支持单个文件在服务间的传输,当传送多个文件时,则会报错:feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [[Lorg.springframework.web.multipart.MultipartFile;] and content type [multipart/form-data]


提示:以下是本篇文章正文内容,下面案例可供参考

一、config配置文件

@Configurable
public class MultipartSupportConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringMultipartEncoder(new SpringEncoder(messageConverters));
    }
}

二、SpringMultipartEncoder 多文件编码解析

重写encode方法,处理多文件

public class SpringMultipartEncoder extends SpringFormEncoder {

    public SpringMultipartEncoder() {
        this(new Default());
    }

    public SpringMultipartEncoder(Encoder delegate) {
        super(delegate);
        MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (bodyType != null && bodyType.equals(MultipartFile.class)) {
            MultipartFile file = (MultipartFile) object;
            if (file != null) {
                Map<String, Object> data = Collections.singletonMap(file.getName(), object);
                super.encode(data, MAP_STRING_WILDCARD, template);
                return;
            }
        } else if (bodyType != null && bodyType.equals(MultipartFile[].class)) {
            MultipartFile[] file = (MultipartFile[]) object;
            if (file != null) {
                Map<String, Object> data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
                super.encode(data, MAP_STRING_WILDCARD, template);
                return;
            }
        }
        super.encode(object, bodyType, template);
    }
}

三、修改Feign接口(客户端),指定配置文件

@FeignClient(value = "XXX", fallbackFactory = XXX.class, configuration = MultipartSupportConfig.class)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值