Feign调用文件下载服务接口实例

简介: Feign调用文件下载服务接口实例

开发使用Feign做微服开发调用客户端时,几乎都是普通接口调用,返回一些JSON数据,

今天刚好要进行Feign客户端(服务消费者)调用服务提供者的文件下载接口,记录一下!代码如下:

服务提供者:

 @PostMapping(value = "/downLoadFile")
    public void downloadFile(@RequestParam String path, HttpServletResponse response) {
        File file = new File(path);
        FileUtil.fileDownload(response, file, false);
    }

FileUtil工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtil {
   private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

   /**
    * 将指定文件对象写入到特定的Servlet响应对象,进而实现下载
    * 一般用于下载已经存在的文件
    *
    * @param response         目标Servlet响应对象
    * @param file             要下载的文件对象
    * @param isDeleteOriginal 是否删除服务器文件原本,true下载后将删除服务器上的文件
    */
   public static void fileDownload(HttpServletResponse response, File file, Boolean isDeleteOriginal) {
       try {
           InputStream inputStream = new FileInputStream(file);
           BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
           response.setContentType("multipart.form-data")
           response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
           BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());

           int length = 0;
           byte[] temp = new byte[1024 * 10];
           while ((length = bufferedInputStream.read(temp)) != -1) {
               bufferedOutputStream.write(temp, 0, length);
           }
           bufferedOutputStream.flush();
           bufferedOutputStream.close();
           bufferedInputStream.close();
           inputStream.close();
           if (isDeleteOriginal) {
               file.delete();
           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
           logger.error(e.getMessage());
       } catch (IOException e) {
           e.printStackTrace();
           logger.error(e.getMessage());
       }
   }
}

Feign客户端(服务消费者)的代码

import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@FeignClient(name = "file-service")
public interface UserFeignClient extends FeignClientParent {
    @GetMapping(value = "/update/downLoadFile",consumes = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
    Response downloadFile(@RequestParam String path);
}

Feign客户端(服务消费者)的Controller接口方法

@GetMapping(value = "/downLoadFile")
    public void downloadFile(@RequestParam String path, HttpServletResponse response) {
        InputStream inputStream = null;
        try {
            Response serviceResponse = this.userFeignClient.downloadFile(path);
            Response.Body body = serviceResponse.body();
            inputStream = body.asInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            response.setContentType("multipart.form-data")
            response.setHeader("Content-Disposition", serviceResponse.headers().get("Content-Disposition").toString().replace("[","").replace("]",""));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            int length = 0;
            byte[] temp = new byte[1024 * 10];
            while ((length = bufferedInputStream.read(temp)) != -1) {
                bufferedOutputStream.write(temp, 0, length);
            }
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
            bufferedInputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这一段代码是为了保持服务提供者一致的文件下载输出,其中就包括文件名!

serviceResponse.headers().get("Content-Disposition").toString().replace("[","").replace("]","")

原理:就是将服务提供者的文件下载响应的响应体(文件内容)复制到服务消费者对外的文件下载响应体中

相关文章
SpringBoot之文件上传(单文件与多文件上传的使用)
SpringBoot之文件上传(单文件与多文件上传的使用)
609 1
|
Java 数据安全/隐私保护 数据格式
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
|
SQL Java 数据库连接
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
|
人工智能 API 开发工具
DIFY的安装以及API配置教程
本指南详解DIFY本地部署全流程:先安装Docker与Git,再克隆GitHub官方仓库(langgenius/dify);接着通过终端完成配置文件复制与初始化(访问http://localhost/install);最后集成CanopyWave插件,配置专属API密钥及模型地址,即可启用企业级AI应用。
5869 3
|
9月前
|
安全 Java API
Spring Boot 4 升级实战:从3.x到4.0的分步升级保姆级指南
Spring Boot 4.0于2025年11月发布,基于Spring Framework 7.0,实现模块化(47个轻量自动配置)、JSpecify空安全校验、原生API版本控制等重大升级。镜像减19%、启动快33%,迁移平滑,3.5.x支持至2026年11月。(239字)
7024 1
|
SQL 存储 关系型数据库
【MySQL技术专题】「实战开发系列」一同探索一下数据库的加解密函数开发实战指南之AES系列
【MySQL技术专题】「实战开发系列」一同探索一下数据库的加解密函数开发实战指南之AES系列
1612 0
|
算法 Java 数据库连接
SpringBoot3分库分表
按照业务拆分的方式称为垂直分片,又称为纵向拆分,它的核心理念是专库专用;水平分片又称为横向拆分,是通过某些字段根据某种规则将数据分散至多个库或表中。
1618 0
|
存储 Java 数据库连接
Mybatis-plus@DS实现动态切换数据源应用
Mybatis-plus@DS实现动态切换数据源应用
2514 0
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,处理前后端日期交互是一个常见问题。本文通过 **@DateTimeFormat** 和 **@JsonFormat** 两个注解,详细讲解了如何解析前端传来的日期字符串以及以指定格式返回日期数据。文章从实际案例出发,结合代码演示两者的使用场景与注意事项,解决解析失败、时区偏差等问题,并提供全局配置与局部注解的实践经验。帮助开发者高效应对日期时间格式化需求,提升开发效率。
4521 2