前言

  最近在项目中使用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. 重温CLR(十四) 可空类型

    我们知道,一个值类型的变量永远不可能为null.它总是包含值类型本身.遗憾的是,这在某些情况下会成为问题.例如,设计一个数据库时,可将一个列定义成为一个32位的整数,并映射到FCL的Int32数据类型 ...

  2. 《selenium2 python 自动化测试实战》(17)——几个cookies操作

    之前我们已经学过利用cookies跳过验证码登录了,那时候我们用的方法是add_cookie()方法,这里再给大家介绍两个,一般情况下我们用不到,了解一下就可以,而且如果真的用到的时候百度也很快的: ...

  3. testem方便的web tdd 测试框架使用

    备注:    单元测试,对于日常的开发是比较重要的,testem 简化了我们的代码编写,以及运行.    主要特性:    a. 支持的测试框架有:jasmine quint mocha buster ...

  4. [深度学习]Wake-Sleep算法

    本文翻译自2007-To recognize shapes, first learn to generate images, Geoffrey Hinton. 第五种策略的设计思想是使得高层的特征提取 ...

  5. Iterations --codility

    lesson 1:Iterations 1. BinaryGap-----[100%] Find longest sequence of zeros in binary representation ...

  6. bzoj1017(JSOI2008)魔兽地图

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1017 钱数很少,所以它也能压进状态里. 还有向上贡献几个物品.所以状态就是第 i 号物品,向 ...

  7. if的用法

    if用法举例:求分数的等级 # include <stdio.h> int main(void) { float score; //score分数 printf("请输入您的考试 ...

  8. js中去掉字符串中的某个指定字符

    假设一个data里面的数据是[tian,12],现在去掉[],代码如下 data=data.replace("[",""); data=data.replace ...

  9. 双口RAM,值得研究

    在FPGA设计过程中,使用好双口RAM,也是提高效率的一种方法. 官方将双口RAM分为简单双口RAM和真双口RAM. 简单双口RAM只有一个写端口,一个读端口. 真双口RAM分别有两个写端口和两个读端 ...

  10. bzoj2184: 任意图的匹配

    Description 每天都要考,每天都要讲,大家注意力都集中不起来了,每天听解题报告时都有人交头接耳(也包括我,呵呵).这样做大大的影响的学习效率(可能吧).于是,有些好奇心重的同学就开始研究,怎 ...