Feign实现文件上传下载
Feign框架对于文件上传消息体格式并没有做原生支持,需要集成模块feign-form来实现。
独立使用Feign
添加模块依赖:
<!-- Feign框架核心 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>11.1</version>
</dependency>
<!-- 支持表单格式,文件上传格式 -->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.8.0</version>
</dependency>
<!-- 文件操作工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
上传文件
定义接口:
public interface FileUploadAPI {
// 上传文件:参数为单个文件对象
@RequestLine("POST /test/upload/single")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("file") File file);
// 上传文件:参数文多个文件对象
@RequestLine("POST /test/upload/batch")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("files") File[] files);
// 上传文件:参数文多个文件对象
@RequestLine("POST /test/upload/batch")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("files") List<File> files);
// 上传文件:参数为文件字节数组(这种方式在服务端无法获取文件名,不要使用)
@RequestLine("POST /test/upload/single")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("file") byte[] bytes);
// 上传文件:参数为FormData对象
@RequestLine("POST /test/upload/single")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("file") FormData photo);
// 上传文件:参数为POJO对象
@RequestLine("POST /test/upload/single")
@Headers("Content-Type: multipart/form-data")
String upload(@Param("file") MyFile myFile);
class MyFile {
@FormProperty("is_public")
Boolean isPublic;
File file;
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
}
调用接口:
FileAPI fileAPI = Feign.builder()
.encoder(new FormEncoder()) // 必须明确设置请求参数编码器
.logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL)
.target(FileAPI.class, "http://localhost:8080");
File file1 = new File("C:\\Users\\xxx\\Downloads\\test1.jpg");
File file2 = new File("C:\\Users\\xxx\\Downloads\\test2.jpg");
// 上传文件1:参数为文件对象
fileAPI.upload(file1);
// 上传文件2:参数为字节数组(注意:在服务端无法获取到文件名)
byte[] bytes = FileUtils.readFileToByteArray(file1);
fileAPI.upload(bytes);
// 上传文件3:参数为FormData对象
byte[] bytes = FileUtils.readFileToByteArray(file1);
FormData formData = new FormData("image/jpg", "test1.jpg", bytes);
String result = fileAPI.upload(formData);
// 上传文件4:参数为POJO对象
FileAPI.MyFile myFile = new FileAPI.MyFile();
myFile.setPublic(true);
myFile.setFile(file1);
fileAPI.upload(myFile);
// 上传文件:参数为多个文件
fileAPI.upload(new File[]{file1, file2});
fileAPI.upload(Arrays.asList(new File[]{file1, file2}));
下载文件
定义接口:
public interface FileDownloadAPI {
// 下载文件
@RequestLine("GET /test/download/file")
Response download(@QueryMap Map<String, Object> queryMap);
}
调用接口:
// 下载文件时返回值为Response对象,不需要设置解码器
FileAPI fileAPI = Feign.builder()
.logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL)
.target(FileAPI.class, "http://localhost:8080");
String fileName = "test.jpg";
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("fileName", fileName);
Response response = fileAPI.download(queryMap);
if (response.status() == 200) {
File downloadFile = new File("D:\\Downloads\\", fileName);
FileUtils.copyInputStreamToFile(response.body().asInputStream(), downloadFile);
}
使用Spring Cloud Feign
在Spring框架中使用Feign实现文件上传时需要依赖feign-form
和feign-form-spring
,这2个模块已经在“Spring Cloud Feign”中自带了,只需要添加spring-cloud-starter-openfeign
依赖即可。
<!-- 集成Spring和Feign,包含了模块feign-form和feign-form-spring -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.0.2</version>
</dependency>
<!-- 文件操作工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
上传文件
定义接口及配置:
@FeignClient(value = "FileAPI", url = "http://localhost:8080", configuration = FileUploadAPI.FileUploadAPIConfiguration.class)
public interface FileUploadAPI {
/**
* 上传单个文件
* @param file
* @return
*/
@RequestMapping(value = "/test/upload/single", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
String upload(@RequestPart("file") MultipartFile file);
/**
* 上传多个文件
* @param files
* @return
*/
@RequestMapping(value = "/test/upload/batch", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
String upload(@RequestPart("files") List<MultipartFile> files);
class FileUploadAPIConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignEncoder () {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
@Bean
public Logger feignLogger() {
return new Slf4jLogger();
}
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
}
调用接口:
// 上传单个文件
File file = new File("C:\\Users\\xxx\\Downloads\\test1.jpg");
FileInputStream fis = new FileInputStream(file);
MockMultipartFile mockMultipartFile = new MockMultipartFile("file", file.getName(), "image/jpg", fis);
this.fileUploadAPI.upload(mockMultipartFile);
fis.close();
// 上传多个文件
File file1 = new File("C:\\Users\\xxx\\Downloads\\test1.jpg");
File file2 = new File("C:\\Users\\xxx\\Downloads\\test2.jpg");
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
MockMultipartFile f1 = new MockMultipartFile("files", file1.getName(), "image/jpg", fis1);
MockMultipartFile f2 = new MockMultipartFile("files", file2.getName(), "image/jpg", fis2);
this.fileUploadAPI.upload(Arrays.asList(new MockMultipartFile[]{f1, f2}));
fis1.close();
fis2.close();
下载文件
定义接口:
@FeignClient(value = "FileDownloadAPI", url = "http://localhost:8080", configuration = FileDownloadAPI.FileDownloadAPIConfiguration.class)
public interface FileDownloadAPI {
/**
* 下载文件
* @param fileName 文件名
* @return
*/
@RequestMapping(value = "/test/download/file", method = RequestMethod.GET)
Response download(@RequestParam("fileName") String fileName);
// 下载文件时返回值为Response对象,不需要设置解码器
class FileDownloadAPIConfiguration {
@Bean
public Logger feignLogger() {
return new Slf4jLogger();
}
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
}
调用接口:
String fileName = "test.jpg";
Response response = this.fileDownloadAPI.download(fileName);
File destFile = new File("D:\\Downloads\\", fileName);
// 使用org.apache.commons.io.FileUtils工具类将输入流中的内容转存到文件
FileUtils.copyInputStreamToFile(response.body().asInputStream(), destFile);
总结
1.Feign框架需要集成模块feign-form才能支持文件上传的消息体格式。
2.不论是独立使用Feign,还是使用Spring Cloud Feign,下载文件时的返回值都必须为feign.Response
类型。
Feign实现文件上传下载的更多相关文章
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- Selenium2学习-039-WebUI自动化实战实例-文件上传下载
通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a ...
- 艺萌文件上传下载及自动更新系统(基于networkComms开源TCP通信框架)
1.艺萌文件上传下载及自动更新系统,基于Winform技术,采用CS架构,开发工具为vs2010,.net2.0版本(可以很容易升级为3.5和4.0版本)开发语言c#. 本系统主要帮助客户学习基于TC ...
- 艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输)(一)
艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输) 该系统基于开源的networkComms通讯框架,此通讯框架以前是收费的,目前已经免费并开元,作者是英国的,开发时间5年多,框架很稳定. 项 ...
- ssh框架文件上传下载
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SpringMVC——返回JSON数据&&文件上传下载
--------------------------------------------返回JSON数据------------------------------------------------ ...
- 【FTP】FTP文件上传下载-支持断点续传
Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...
- NetworkComms 文件上传下载和客户端自动升级(非开源)
演示程序下载地址:http://pan.baidu.com/s/1geVfmcr 淘宝地址:https://shop183793329.taobao.com 联系QQ号:3201175853 许可:购 ...
随机推荐
- Flutter 让你的Dialog脱胎换骨吧!(Attach,Dialog,Loading,Toast)
前言 Q:你一生中闻过最臭的东西,是什么? A:我那早已腐烂的梦. 兄弟萌!!!我又来了! 这次,我能自信的对大家说:我终于给大家带了一个,能真正帮助大家解决诸多坑比场景的pub包! 将之前的flut ...
- Django在使用logging日志模块时报错无法操作文件 logging error Permission Error [WinError 32]
产生原因: 这个问题只会在开发的时候遇到,而且配置是写入到setting.py配置文件,我们定义了日志文件大小,当日志满了的时候,这时候就会遇到这个问题, 因为在使用Pycharm运行django的时 ...
- git报错 error: cannot stat 'file': Permission denied
切换分支(git checkout xxx)时报错: error: cannot stat 'file': Permission denied 解决方法:退出编辑器.浏览器.资源管理器等,然后再切换就 ...
- Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256M; support was removed in 8.0
目录 启动一个Java Standalone程序时报错 解决办法 解释 参考 启动一个Java Standalone程序时报错 Java HotSpot(TM) 64-Bit Server VM wa ...
- 【Warrior刷题笔记】剑指offer 32. 三道题,让你学会二叉树的深度广度优先遍历与递归迭代技术
题目一 剑指 Offer 32 - I. 从上到下打印二叉树 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xi ...
- 手写Webserver
一.反射 反射Reflection:把java类中的各种结构(方法.属性.构造器.类名)映射成一个个的java对象.利用反射技术可以对一个类进行解剖,反射是框架设计的灵魂 //在运行期间,一个类,只有 ...
- Springboot集成邮箱服务发送邮件
一.前言 Spring Email 抽象的核心是 MailSender 接口,MailSender 的实现能够把 Email 发送给邮件服务器,由邮件服务器实现邮件发送的功能. Spring 自带了一 ...
- [爱偷懒的程序员系列]-Section 1. “懒”是一切需求的根源
一直认为"懒"推进了科技的发展,因为"懒"而促生了各种各样的需求.科技的进步加速了各种信息的交互频率,站在台面上说是因为业务需要提高效率,成本需要降低,服务需要 ...
- 在pyqt5中展示pyecharts生成的图像
技术背景 虽然现在很少有人用python去做一些图形化的界面,但是不得不说我们在日常大部分的软件使用中都还是有可视化与交互这样的需求的.因此pyqt5作为一个主流的python的GUI框架地位是非常重 ...
- Android一句话 | ViewGroup事件分发
ViewGroup中可重写的关于事件分发的事件有dispatchTouchEvent,onTouchEvent,onInterceptTouchEvent和requestDisallowInterce ...