Spring Cloud Feign实现文件上传下载的示例代码

目录
  • 独立使用Feign
    • 上传文件
    • 下载文件
  • 使用Spring Cloud 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类型。

到此这篇关于 Spring Cloud Feign实现文件上传下载的示例代码的文章就介绍到这了,更多相关 Spring Cloud Feign文件上传下载内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring Cloud中FeignClient实现文件上传功能

    项目概况:Spring Cloud搭的微服务,使用了eureka,FeignClient,现在遇到FeignClient调用接口时不支持上传文件, 百度到两种方案,一种是使用feign-form和feign-form-spring库来做,源码地址. 具体的使用方法是加入maven依赖 <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring&l

  • Spring Cloud Feign的文件上传实现的示例代码

    在Spring Cloud封装的Feign中并不直接支持传文件,但可以通过引入Feign的扩展包来实现,本来就来具体说说如何实现. 服务提供方(接收文件) 服务提供方的实现比较简单,就按Spring MVC的正常实现方式即可,比如: @RestController public class UploadController { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VAL

  • SpringCloud使用Feign文件上传、下载

    文件上传.下载也是实际项目中会遇到的场景,本篇我们介绍下springcloud中如何使用feign进行文件上传与下载. 还是使用feign 进行http的调用. 一.Feign文件上传 服务提供方java代码: /** * 文件上传 * @param file 文件 * @param fileType * @return */ @RequestMapping(method = RequestMethod.POST, value = "/uploadFile", produces = {

  • 使用Spring Cloud Feign上传文件的示例

    最近经常有人问Spring Cloud Feign如何上传文件.有团队的新成员,也有其他公司的兄弟.本文简单做个总结-- 早期的Spring Cloud中,Feign本身是没有上传文件的能力的(1年之前),要想实现这一点,需要自己去编写Encoder 去实现上传.现在我们幸福了很多.因为Feign官方提供了子项目feign-form ,其中实现了上传所需的 Encoder . 注:笔者测试的版本是Edgware.RELEASE.Camden.Dalston同样适应本文所述. 加依赖 <depen

  • Spring Cloud Feign实现文件上传下载的示例代码

    目录 独立使用Feign 上传文件 下载文件 使用Spring Cloud Feign 上传文件 下载文件 总结 Feign框架对于文件上传消息体格式并没有做原生支持,需要集成模块feign-form来实现. 独立使用Feign 添加模块依赖: <!-- Feign框架核心 --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-core</arti

  • Go Gin实现文件上传下载的示例代码

    Go Gin 实现文件的上传下载流读取 文件上传 router router.POST("/resources/common/upload", service.UploadResource) service type: POST data:{ "saveDir":"保存的路径", "fileName":"文件名称不带后缀" } // 上传文件 func UploadResource(c *gin.Conte

  • Koa2 之文件上传下载的示例代码

    前言 上传下载在 web 应用中还是比较常见的,无论是图片还是其他文件等.在 Koa 中,有很多中间件可以帮助我们快速的实现功能. 文件上传 在前端中上传文件,我们都是通过表单来上传,而上传的文件,在服务器端并不能像普通参数一样通过 ctx.request.body 获取.我们可以用 koa-body 中间件来处理文件上传,它可以将请求体拼到 ctx.request 中. // app.js const koa = require('koa'); const app = new koa(); c

  • Spring Boot + thymeleaf 实现文件上传下载功能

    最近同事问我有没有有关于技术的电子书,我打开电脑上的小书库,但是邮件发给他太大了,公司又禁止用文件夹共享,于是花半天时间写了个小的文件上传程序,部署在自己的Linux机器上. 提供功能: 1 .文件上传 2.文件列表展示以及下载 原有的上传那块很丑,写了点js代码优化了下,最后界面显示如下图: 先给出成果,下面就一步步演示怎么实现. 1.新建项目 首先当然是新建一个spring-boot工程,你可以选择在网站初始化一个项目或者使用IDE的Spring Initialier功能,都可以新建一个项目

  • java文件上传下载功能实现代码

    本文实例为大家分享了文件上传下载java实现代码,供大家参考,具体内容如下 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type="file" /> 3. 指定表单类型:     默认类型:enctype="application/x-www-form-urlencoded"     文件上传类型:multipart/form-data FileUpload 文件上传功能开发中比较常用,apache也提供了文件上传组

  • Struts2 控制文件上传下载功能实例代码

    之前介绍servlet3.0新特性的时候有提到过servlet API提供了一个part类来实现对文件的上传和保存,Struts其实是在其基础上做了进一步的封装,更加简单易用.至于文件下载,Struts贯彻AOP 思想,在下载之前提供对用户权限控制的API. 下面我们将详细介绍上传和下载的相关内容. 一.Struts文件上传机制 想要实现文件上传功能,页面的表单的method属性必须被指定为post,还有enctype属性必须为multipart/form-data,该值表示上传的内容将会以二进

  • JavaWeb文件上传下载功能示例解析

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 1. 上传简单示例 Jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"&g

  • servlet+jquery实现文件上传进度条示例代码

    现在文件的上传,特别是大文件上传,都需要进度条,让客户知道上传进度. 本文简单记录下如何弄进度条,以及一些上传信息,比如文件的大小,上传速度,预计剩余时间等一些相关信息.代码是匆忙下简单写的,一些验证没做,或代码存在一些隐患,不严谨的地方.本文代码只供参考. 进度条的样式多种多样,有些网站弄得非常绚烂漂亮.本文UI端不太懂,只会一些简单的基本的css而已,所以进度条弄得不好看.本文侧重的给读者提供一个参考,一个实现思路而已. 注:由于jQuery版本用的是2.1.1,所以如果跑本例子源码,请用I

  • Spring Boot实现文件上传下载

    本文实例为大家分享了Spring Boot实现文件上传下载的具体代码,供大家参考,具体内容如下 示例[Spring Boot  文件上传下载] 程序清单:/springboot2/src/main/resources/templates/register.html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8

随机推荐