java实现本地文件转文件流发送到前端

java实现本地文件转文件流发送到前端

Controller

java 复制代码
  public void export(HttpServletResponse response) {
   // 创建file对象
      response.setContentType("application/octet-stream");
      // 文件名为 s
      response.setHeader("Content-Disposition", "attachment;fileName=" + s);
      FileUtils.writeBytes(fileName, response.getOutputStream());
  }

FileUtils

java 复制代码
 public static void writeBytes(String filePath, OutputStream os) throws IOException{
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            IOUtils.close(os);
            IOUtils.close(fis);
        }
    }

如果是临时文件需要删除

controller

java 复制代码
  public void repairStatisticListExport(HttpServletResponse response) {
   // 创建file对象
      response.setContentType("application/octet-stream");
      // 文件名为 s
      response.setHeader("Content-Disposition", "attachment;fileName=" + s);
      FileUtils.writeBytes(fileName, response.getOutputStream());
      FileUtils.deleteFile(fileName);
  }

deleteFile方法

java 复制代码
  public static boolean deleteFile(String filePath) {
    boolean flag = false;
    File file = new File(filePath);
    // 路径为文件且不为空则进行删除
    if (file.isFile() && file.exists()) {
      file.delete();
      flag = true;
    }
    return flag;
  }

临时文件路径

java 复制代码
  public static String getDefaultBaseDir() {
    String os = System.getProperty("os.name");
    if (os.toLowerCase().startsWith("windows")) {
      return "C:/uploadPath/";
    } else if (os.toLowerCase().startsWith("linux")) {
      return "/home/uploadPath/";
    }
    return "/home/uploadPath/";
  }
相关推荐
文丑颜不良啊9 分钟前
LeetCode2021~2040题目解析
java·leetcode
bksczm30 分钟前
InnoDB 行格式详解:DYNAMIC / COMPACT / COMPRESSED / REDUNDANT
java·开发语言·数据库
liangbo71 小时前
Spring系列03:Bean 的三种注册方式
java·spring
余槐i1 小时前
MySQL 8.0 联合索引走错:为什么加了索引查询反而从 200ms 变成 8s
java·spring boot·mysql·docker·性能优化
SL_staff1 小时前
制造业订单交付总在最后一刻爆雷?用结构化计划模板打通跨系统协同断点
java·开源·全栈
做科研的周师兄1 小时前
【R语言实战】MixSIAR 氢氧同位素水源解析全流程:从混合空间校验到贝叶斯 MCMC 收敛诊断(后附完整代码)
java·大数据·开发语言
有点小困9771 小时前
Spring Boot 异步任务 ClassLoader 踩坑实录:ClassNotFoundException 的诡异真相
java
aiks_yuan2 小时前
Java 正则表达式很慢怎么办:Pattern 预编译只快 2~5 倍,真正卡死线程的是回溯(JDK 8、11、17 实测)
java
用户3721574261352 小时前
C# 填写 PDF 交互式表单:文本框、复选框、单选按钮和下拉列表
java
IT枫斗者枫哥2 小时前
Java 退款请求超时,先查原单还是重试?
java·后端