最近项目中遇到了使用feign调用附件上传接口无法传参问题,我这边multipart类型数据没有问题,服务端接收到的file就是一直为null。浪费我大半天时间,终于还是完美解决了。这是我项目引用的依赖,由于spring-cloud-starter-openfeign默认不支持传附件,所以需要引入新的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
以下是我的解决步骤,希望能帮助遇到同样问题的同学们!!!
1、首先在pom.xml引入相应的依赖
<!-- 解决feign调用无法传MultipartFile -->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.8.0</version>
</dependency>
2、然后重写FeignMultipartSupportConfig
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
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;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
/**
* 多实例,在IOC容器启动创建的时候,并不会直接创建对象放在容器中去,当你需要调用的时候,才会从容器当中获取该对象然后进行创建。
* @author tianlong
* @version 1.0
* @date 2024/1/31 12:52
*/
@Configuration
public class FeignMultipartSupportConfig {
private final ObjectFactory<HttpMessageConverters> messageConverters;
public FeignMultipartSupportConfig(ObjectFactory<HttpMessageConverters> messageConverters) {
this.messageConverters = messageConverters;
}
@Bean
@Primary
@Scope("prototype")
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
@Bean
public feign.Logger.Level multipartLoggerLevel() {
return feign.Logger.Level.FULL;
}
}
3、引用刚重写的配置类FeignMultipartSupportConfig
4、调用端代码
@PostMapping(value = "/upload/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> uploadImage(@RequestPart(value = "file") MultipartFile file);
注意:consumes = MediaType.MULTIPART_FORM_DATA_VALUE此处为固定写法,指定类型为 "multipart/form-data"。参数用@RequestPart() 也是固定写法,value的值要和被调用的服务端值保持一致,因为服务端接收的参数是file,所以我这边是@RequestPart(value = "file")
附、被调用服务端代码
@PostMapping("image")
@ApiOperation(value = "上传图片", httpMethod = "POST")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
String url = uploadService.uploadImage(file);
return ResponseEntity.ok(url);
}
到此处问题就完美解决了,第一次写文章,各位大佬们有什么建议,接受批评,欢迎留言!!!