前言

  最近在项目中使用OpenFeign时,发现其不支持文件上传功能。网上找了很多资料,最后找到feign-form和feign-form-spring的解决方案。但其默认只支持单文件上传,不支持多文件上传。解决办法为:重写Encoder类,详见三。

一、配置

1. 引入依赖

<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.3.0</version>
</dependency>

2. 在调用方增加配置

@Configuration
public class AdminWebMvcConfig implements WebMvcConfigurer {
@Bean
public Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}

3. 调用方启动类配置

@EnableFeignClients(basePackages = {"com.xxx.xxx"})
@SpringCloudApplication
@Import({AdminWebMvcConfig.class})
public class WebAdminApplication { public static void main(String[] args) {
SpringApplication.run(WebAdminApplication.class, args);
} }

二、单文件上传代码实现

  • 服务调用方、接口和提供方,都使用@RequestPart注解
  • 标记MediaType.MULTIPART_FORM_DATA_VALUE

1. 服务提供方Controller

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public String upload(@RequestPart(value = "file") MultipartFile file) {   ......
}

2. FeignClient接口

@FeignClient(name = "xxx")
public interface FileUploadApiClient {
  /**
  * 文件上传
  */
  @PostMapping(value = "/oss/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  String upload(@RequestPart(value = "file") MultipartFile file); }

3. 调用方Controller

@RestController
public class FileUploadManagerController {   @Autowired
  private FileUploadApiClient fileUploadApiClient;   @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  @ResponseBody
  public String upload(@RequestPart(value = "file") MultipartFile file) {
    return fileUploadApiClient.upload(file);
  }
}

三、多文件上传实现

  •  只需修改下面两项,即可完美支持单文件和多文件上传功能

1. 新建FeignSpringFormEncoder类

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.form.ContentType;
import feign.form.FormEncoder;
import feign.form.MultipartFormContentProcessor;
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; public class FeignSpringFormEncoder extends FormEncoder { /**
* Constructor with the default Feign's encoder as a delegate.
*/
public FeignSpringFormEncoder() {
this(new Default());
} /**
* Constructor with specified delegate encoder.
*
* @param delegate delegate encoder, if this encoder couldn't encode object.
*/
public FeignSpringFormEncoder(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.equals(MultipartFile.class)) {
MultipartFile file = (MultipartFile) object;
Map data = Collections.singletonMap(file.getName(), object);
super.encode(data, MAP_STRING_WILDCARD, template);
return;
} else if (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);
}
}

2. 修改AdminWebMvcConfig

@Configuration
public class AdminWebMvcConfig implements WebMvcConfigurer { @Bean
public Encoder feignEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
return new FeignSpringFormEncoder(new SpringEncoder(messageConverters));
}
}

参考:https://blog.csdn.net/ytzzh0726/article/details/79467843

解决OpenFeign默认无法上传文件的问题的更多相关文章

  1. 解决COS、FileUpload上传文件时中文文件名乱码问题

    方法: MultipartParser mp = new MultipartParser(request, 10*1024*1024); mp.setEncoding("GBK") ...

  2. 怎样用纯HTML和CSS更改默认的上传文件按钮样式

    如果你曾经试过,你就会知道,用纯CSS样式加HTML实现统一的上传文件按钮可能会很麻烦.看看下面的不同浏览器的截图.很明显的,他们长得很不一样. 我们的目标是创造一个简洁,用纯CSS实现的,在所有浏览 ...

  3. Java如何解决form表单上传文件,以及页面返回处理结果通知!

    前端JSP代码 <form id='formSumbit' class='form-horizontal' action='/ncpay/route/chlsubmcht/batchImpor' ...

  4. php_admin_value open_basedir 引起的上传文件失败解决方法

    为了安全,我们通常会在虚拟主机设置中,加入这一行php_admin_value open_basedir "/usr/local/apache/htdocs/www"但这会导致mo ...

  5. flask插件系列之flask_uploads上传文件

    前言 flask可以实现上传文件和下载文件的基本功能,但如果想要健壮的功能,使用flask_uploads插件是十分方便的. 安装 pip install flask_uploads 基本使用 # e ...

  6. Spring Boot应用上传文件时报错

    问题描述 Spring Boot应用(使用默认的嵌入式Tomcat)在上传文件时,偶尔会出现上传失败的情况,后台报错日志信息如下:"The temporary upload location ...

  7. asp.net 上传文件超过了最大请求长度

    今天系统遇到了一个问题,上传4m以上的文件,uploadify就会报错:超过了最大请求长度. 开始我以为是设置的大小,可是后来我看了uploadify的fileSizeLimit=1024*10,也就 ...

  8. Nginx上传文件失败

    公司用Nginx做反向代理,出现了上传文件失败的问题,通过查看错误日志,发现是上传文件太大的缘故. 通过查找资料,才知道nginx默认最大上传文件时1M.这就需要修改配置文件,将上传文件大小进行修改. ...

  9. asp.net上传文件超过了最大请求长度[转]

    错误消息:超过了最大请求长度    错误原因:asp.net默认最大上传文件大小为4M,运行超时时间为90S.   解决方案 1. 修改web.config文件可以改变这个默认值            ...

随机推荐

  1. python 数组反序的方法

    arr = np.array(some_sequence) reversed_arr = arr[::-1] do_something(arr) look_at(reversed_arr) do_so ...

  2. Tencent Server Web(TSW) 腾讯开源的nodejs 基础设施

      Tencent Server Web(TSW),是一套面向WEB前端开发者,以提升问题定位效率为初衷,提供染色抓包.全息日志和异常发现的Node.js基础设施.TSW关注业务的运维监控能力,适用于 ...

  3. 中兴G718C开发者模式开启

    系统设置--关于手机--版本号,连按七次,打开开发者选项 请进入设置——连接到PC——默认连接类型——安装驱动,选择即可.然后将手机和电脑连接,打开“我的电脑”或“计算机”会弹出可移动盘符“USB D ...

  4. Linux服务器运维安全策略经验分享

    http://jxtm.jzu.cn/?p=3692 大家好,我是南非蚂蚁,今天跟大家分享的主题是:线上Linux服务器运维安全策略经验.安全是IT行业一个老生常谈的话题了,从之前的“棱镜门”事件中折 ...

  5. 安装xamp之后,appach、mysql等问题的总结

    问题一:无法启动的问题 如果他们无法启动,大多数情况是端口号被占用. 首先就是查看端口号:点击“netstart“按钮查看端口号的使用详情 如果被占用就点击"config”按钮,进行端口号的 ...

  6. RK3288 error: undefined reference to 'LOGD'

    HAL层和JNI层中的打印都必须包含下面的宏和头文件. 比如:LOGD.LOGE等等. #define LOG_TAG "TEST_LED" #include <utils/ ...

  7. REST API权限集成设计

    REST API权限集成设计 应用分为两大部分,前端html+后端Rest服务,前端html和后端Rest服务部署完全分离. 目标:可访问资源都处于权限控制之下(意味着通过浏览器地址栏的任意url都会 ...

  8. Spring AOP两种实现方式

    一. AOP 概念: Spring AOP 即Aspect Oriented Programming(面向切面编程), 实现方式分为两种: 1. 注解(Annotation) 2. 配置(Config ...

  9. [转]SVN 乱码问题

    以下来自:http://godchenmeng.iteye.com/blog/797727 最近研究SVN.发现在创建补丁包的时候出现这种情况. 在文件顶部不论是什么代码都会变成乱码.在文件中如果有注 ...

  10. python学习 (三十二) 异常处理

    1 异常: def exceptionHandling(): try: a = b = d = a / b print(d) except ZeroDivisionError as ex: print ...