千家信息网

怎么用Spring Cloud Feign实现文件上传下载

发表于:2024-10-25 作者:千家信息网编辑
千家信息网最后更新 2024年10月25日,这篇"怎么用Spring Cloud Feign实现文件上传下载"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获
千家信息网最后更新 2024年10月25日怎么用Spring Cloud Feign实现文件上传下载

这篇"怎么用Spring Cloud Feign实现文件上传下载"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"怎么用Spring Cloud Feign实现文件上传下载"文章吧。

    Feign框架对于文件上传消息体格式并没有做原生支持,需要集成模块feign-form来实现。

    独立使用Feign

    添加模块依赖:

        io.github.openfeign    feign-core    11.1    io.github.openfeign.form    feign-form    3.8.0    commons-io    commons-io    2.11.0

    上传文件

    定义接口:

    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 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 queryMap);}

    调用接口:

    // 下载文件时返回值为Response对象,不需要设置解码器FileAPI fileAPI = Feign.builder()                .logger(new Slf4jLogger())                .logLevel(Logger.Level.FULL)                .target(FileAPI.class, "http://localhost:8080");String fileName = "test.jpg";Map 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依赖即可。

        org.springframework.cloud    spring-cloud-starter-openfeign    3.0.2    commons-io    commons-io    2.11.0

    上传文件

    定义接口及配置:

    @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 files);    class FileUploadAPIConfiguration {        @Autowired        private ObjectFactory 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);

    以上就是关于"怎么用Spring Cloud Feign实现文件上传下载"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

    文件 参数 对象 接口 内容 多个 上传下载 单个 文件名 模块 字节 数组 文章 框架 知识 篇文章 解码器 服务 价值 大部分 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 物联网网络安全的特点 垦卓优品互联网科技发展有限公司 徐汇区网络技术信息推荐 黑客为什么要删除数据库 战地五机器人服务器怎么加 曲阜互联网科技有限公司 康舒550w服务器电源如何启动 网络安全股票怎么走 鸿蒙软件开发的基础知识 数据库建模前端 网零服务器 软件开发roadmap 云数据库产品呈现出百家争鸣态势 网络安全与文化的联系 数据库日志是什么意思 浦东新区网络技术转让技术指导 广州网络安全有关的公司 平台买一个服务器需要多少钱 uefi系统盘换到其他服务器上 会计数据库应用技术 盐城网络安全准入控制系统价格 上海灏佳互联网科技中心 安徽党员教育软件开发电话 贵州ipfs服务器配置云主机 理解计算机网络技术 网络技术实践考试 规范网络安全相关制度 招商银行软件开发的工作 计算机网络技术学校专业排行 依法治市网络安全周
    0