今天给大家介绍下在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