Feign实现多文件上传,Open Feign多文件上传问题及解决

 更新时间:2022年11月23日 10:16:07   作者:By子诺  
这篇文章主要介绍了Feign实现多文件上传,Open Feign多文件上传问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Feign实现多文件上传,Open Feign多文件上传解决

废话不多说,直接上代码

  • 用feign多文件上传的Controller代码如下
@Slf4j
@RestController
@RequestMapping("/store")
@Api(description = "店铺管理接口", tags = "店铺管理接口")
public class StoreController {
    @Autowired
    private StoreService storeService;
    
    @ApiOperation(value = "新增店铺信息")
    @PostMapping(value = "/addStoreInfo")
    public Result<Store> addStoreInfo(@Valid @ApiParam(value = "添加店铺时的店铺") StoreDto storeDto, MultipartFile[] multipartFiles) {
        return storeService.addStoreInfo(storeDto,multipartFiles);
    }
}
  • FeignClient代码如下
/**
 * FileName: FileService
 * Author:   SixJR.
 * Date:     2022/3/2 18:38:56
 * Description: 文件RPC服务接口
 * History:
 * <author>          <time>          <version>          <desc>
 */
@FeignClient(name = FeignServiceNameConstants.FILE_SERVICE, fallbackFactory = FileServiceFallbackFactory.class, decode404 = true)
public interface FileService {

    @PostMapping(value = "/enclosure/upload/{objectName}/{objectId}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Result upload(@PathVariable("objectName")String objectName, @PathVariable("objectId")String objectId,@RequestPart("multipartFiles") MultipartFile[] multipartFiles);

}

Feign调用服务,传送类似MultipartFile[] multipartFiles多文件的时候

会出现如下错误

Could not write request: no suitable HttpMessageConverter found for request type [[Lorg.springframework.web.multipart.MultipartFile;] and content type [multipart/form-data]"

错误是因为Feign在组装MultipartFile[] multipartFiles多文件的时候出现了问题

解决这个问题可以重写SpringFormEncoder这个类

重写后的代码如下:

import feign.form.ContentType;
import feign.form.MultipartFormContentProcessor;
import feign.form.spring.SpringFormEncoder;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.form.spring.SpringManyMultipartFilesWriter;
import feign.form.spring.SpringSingleMultipartFileWriter;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Map;

/**
 * FileName: SpringMultipartEncoder
 * Author:   SixJR.
 * Date:     2022/3/2 19:54:12
 * Description: Feign实现多文件上传,重写SpringFormEncoder
 * History:
 * <author>          <time>          <version>          <desc>
 */
public class SpringMultipartEncoder extends SpringFormEncoder {
    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 data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
                super.encode(data, MAP_STRING_WILDCARD, template);
                return;
            }
        }
        super.encode(object, bodyType, template);
    }
}
  • 配置类如下
package com.chinared.common.config;

import com.chinared.common.utils.SpringMultipartEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import feign.codec.Encoder;
import org.springframework.context.annotation.Configuration;

/**
 * FileName: MultipartSupportConfig
 * Author:   SixJR.
 * Date:     2022/3/2 19:56:43
 * Description: 解决Feign在组装MultipartFile[]的时候出现的问题
 * History:
 * <author>          <time>          <version>          <desc>
 */

@Configuration
public class MultipartSupportConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

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

最后在FeignClient指定一下调用类就好啦~

package com.chinared.common.feign;

import com.chinared.common.config.MultipartSupportConfig;
import com.chinared.common.constant.FeignServiceNameConstants;
import com.chinared.common.feign.fallback.FileServiceFallbackFactory;
import com.chinared.common.model.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * FileName: FileService
 * Author:   SixJR.
 * Date:     2022/3/2 18:38:56
 * Description: 文件RPC服务接口
 * History:
 * <author>          <time>          <version>          <desc>
 */
@FeignClient(name = FeignServiceNameConstants.FILE_SERVICE, fallbackFactory = FileServiceFallbackFactory.class, decode404 = true,configuration = MultipartSupportConfig.class)
public interface FileService {

    @PostMapping(value = "/enclosure/upload/{objectName}/{objectId}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Result upload(@PathVariable("objectName")String objectName, @PathVariable("objectId")String objectId,@RequestPart("multipartFiles") MultipartFile[] multipartFiles);

}

好啦,本篇关于OpenFeign支持多文件上传的解决方案就到这啦~

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot SpringSecurity JWT实现系统安全策略详解

    SpringBoot SpringSecurity JWT实现系统安全策略详解

    Spring Security是Spring的一个核心项目,它是一个功能强大且高度可定制的认证和访问控制框架。它提供了认证和授权功能以及抵御常见的攻击,它已经成为保护基于spring的应用程序的事实标准
    2022-11-11
  • 新建一个springboot单体项目的教程

    新建一个springboot单体项目的教程

    这篇文章主要介绍了新建一个springboot单体项目的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-04-04
  • Apache Commons Config管理配置文件核心功能使用

    Apache Commons Config管理配置文件核心功能使用

    这篇文章主要为大家介绍了Apache Commons Config管理和使用配置文件核心深入探索,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java实现中英文词典功能

    Java实现中英文词典功能

    这篇文章主要为大家详细介绍了Java实现中英文词典功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • Java如何优雅的实现微信登录注册

    Java如何优雅的实现微信登录注册

    这篇文章主要给大家介绍了关于Java如何优雅的实现微信登录注册的相关资料,文中通过实例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友可以参考下
    2022-02-02
  • java 实现判断回文数字的实例代码

    java 实现判断回文数字的实例代码

    这篇文章主要介绍了java 实现判断回文数字的实例代码的相关资料,需要的朋友可以参考下
    2017-03-03
  • SpringBoot实现接口幂等性的4种方案

    SpringBoot实现接口幂等性的4种方案

    这篇文章主要介绍了SpringBoot实现接口幂等性的4种方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • 浅谈java中的一维数组、二维数组、三维数组、多维数组

    浅谈java中的一维数组、二维数组、三维数组、多维数组

    下面小编就为大家带来一篇浅谈java中的一维数组、二维数组、三维数组、多维数组。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • spring boot(三)之Spring Boot中Redis的使用

    spring boot(三)之Spring Boot中Redis的使用

    这篇文章主要介绍了spring boot(三)之Spring Boot中Redis的使用,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-05-05
  • Java行为型模式中命令模式分析

    Java行为型模式中命令模式分析

    在软件设计中,我们经常需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是哪个,我们只需在程序运行时指定具体的请求接收者即可,此时可以使用命令模式来进行设计
    2023-02-02

最新评论