日常踩坑_使用Feign访问第三方上传文件接口

之前一直以为当想要以Feign的方式访问第三方接口上文件时,只要传一个文件的参数即可,试过之后才知道这样想也太天真了

Pom文件中添加上传表单的依赖

<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>

这两个依赖是必须要加的,否则会一直报错

写一个Feign的配置类

这个配置类保证了文件传输和实体传输都可以完成

@Configuration
public class FeignConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}

如果需要打开日志
在配置类中再注入一个Bean

@Bean
public feign.Logger.Level multipartLoggerLevel() {
return feign.Logger.Level.FULL;
}

编写FeignClient客户端

以下以企业微信上传临时文件的接口为例

@Primary
@FeignClient(name = "vxClient",
url = "https://qyapi.weixin.qq.com/cgi-bin")
public interface VxFeignClient {
@PostMapping(value = "/media/upload",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
)
WorkVxUploadResponse uploadFile(@RequestParam("type") String type, @RequestPart("media") MultipartFile file);
@GetMapping(value = "media/get")
String getFile(@RequestParam("media_id") String mediaId);
}

注意这里的produces和consumes是非常重要的配置项,表明了提交的是表单

在Service层应用

@Autowired
private VxFeignClient vxFeignClient;
public ResultVo<String> uploadFile(String title) {
//注意这里的"media"一定要和VxFeignClient中uploadFile的@RequestPart("media")一致
MultipartFile multipartFile = new MockMultipartFile("media", "text.xlsx", MediaType.MULTIPART_FORM_DATA_VALUE, new FileInputStream("D:\\test.xlsx"));
uploadRes = vxFeignClient.uploadFile("file", multipartFile);
return result;
}

跳坑完毕,祝各位顺利

posted @   Dean_001  阅读(969)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示