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/";
  }
相关推荐
Nazarick18 分钟前
从 fetch 到 then:Demo在线订单系统 Ajax 回调的逐帧拆解
java·javascript·ajax·web
智购科技自动售货机厂家33 分钟前
自动售货机外设接口与总线设计实战:串口、CAN 与 GPIO 的分工~YH
java·大数据·服务器·数据库·人工智能·单片机·嵌入式硬件
路灯上の马陈1 小时前
Java File类2 练习 学习笔记
java·笔记·学习
Shaoshing1 小时前
LeetCode100 155.最小栈
java·数据结构·算法
SummerJokes1 小时前
Java 多线程专项实验|两种创建线程方式、synchronized 线程同步、银行存取款实战
java·开发语言·python
二宝哥2 小时前
07.Spring AI 接入智谱文生图:从配置到实战
java·人工智能·spring
秋天的怀念_David2 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
xyphf_和派孔明2 小时前
第九章: 上下文工程五大策略与六大模块交叉矩阵纵览
java·开发语言
device_Any2 小时前
线上CPU飙高,排查先分清三种形态
java·后端开发