为了账号安全,请及时绑定邮箱和手机立即绑定

Feign上传文件

标签:
架构

今天给大家介绍下在Feign中如何调用文件上传接口,进行文件上传操作。

这边文章讲的Feign不是Spring Cloud Feign,是原始Feign的使用。

在一些比较老的,不是Spring Cloud的项目中,我们也可以用Feign来进行接口的调用。

使用Feign来上传文件,首先你得有一个上传文件的接口,我们假设上传地址如下:

POST http://localhost:8080/file/upload

参数的话就一个file,一个二进制文件。

在项目中增加Feign的依赖,除了核心模块还有jackson,最重要的就是form模块的依赖,否则无法上传文件。

<dependency>
    <groupId>com.netflix.feign</groupId> 
    <artifactId>feign-core</artifactId>
    <version>8.18.0</version></dependency><dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>2.0.5</version></dependency><dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>8.18.0</version></dependency>

定义一个上传的接口:

public interface FileUploadApi { 
    @RequestLine("POST /file/upload")    @Headers("Content-Type: multipart/form-data")    Response uploadFile(@Param("file") File file);
 
}

@Param("file")byte[] file 也可以

编写上传逻辑:

public class UploadService {    private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8080/file/upload";  
    public boolean uploadFile(File file) {
 
        FileUploadApi fileUploadApi = Feign.builder()
                .encoder(new FormEncoder(new JacksonEncoder()))
                .target(FileUploadApi .class, HTTP_FILE_UPLOAD_URL);
 
        Response response = fileUploadApi .uploadFile(file);        return response.status() == 200;
    }
 
}

测试代码:

 @Test
 public void testUploadFile() {
     UploadService uploadService = new UploadService();
     File file = new File("E:\\yinjihuan.txt");
     assertTrue(uploadService.uploadFile(file));
 }



作者:尹吉欢
链接:https://www.jianshu.com/p/90b6c357d691


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
数据库工程师
手记
粉丝
42
获赞与收藏
202

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消