项目场景:
需要导入Excel,文件传输,我们使用的spring-cloud-starter-openfeign包里发现不存在feign-form-spring 以及 feign-form,所以需要额外引用和配置
问题描述:
刚开始一直文件传递不过去,后来报错

解决方案:
看了别人的文章,结合自己的项目,报错是因为api引用了高版本的包,web层没引用,最后不支持,在web层引用了低版本的包。最后解决方案如下:
pom包引用
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>2.1.0</version>
</dependency>
编写配置类
package com.bjcib.api.config;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
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 org.springframework.context.annotation.Configuration;
@Configuration
public class MultipartSupportConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
controller 调用层
/**
* 上传结算单据
*/
@PostMapping(value = "/addBillFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Resp addBillFile(@RequestParam("file") MultipartFile file, @RequestParam("settlementBillId") Long settlementBillId)
api 层:
/**
* 上传保司Excel
*/
@PostMapping(value = "/micros/settlementBill/addBillFile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Resp addBillFile(@RequestPart("file") MultipartFile file, @RequestParam("settlementBillId") Long settlementBillId);
服务层controller:
/**
* 添加结算单
*
* @param
* @return
*/
@PostMapping(value = "/addBillFile")
public Resp addBillFile(@RequestParam("file") MultipartFile file, @RequestParam("settlementBillId") Long settlementBillId)
需要注意:web层和api层 都需要 consumes = MediaType.MULTIPART_FORM_DATA_VALUE
只有api层的参数需要使用@RequestPart("file") MultipartFile file
pom包引用注意事项:3.5版本的发现不支持,所以用的文中的2.1.0
参考链接:https://blog.csdn.net/shuoshuo132/article/details/81200936
在SpringCloud项目中,文件上传遇到问题,由于缺少feign-form-spring和feign-form依赖,导致文件无法正常传输。报错源于api层引用高版本包,而web层引用低版本,通过在web层引入相同低版本包并配置,同时确保web层和api层都设置consumes为MULTIPART_FORM_DATA_VALUE,并正确使用@RequestPart注解,问题得到解决。
411

被折叠的 条评论
为什么被折叠?



