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/";
  }
相关推荐
Rsun04551几秒前
14、Java 模板方法模式从入门到实战
java·python·模板方法模式
沐雪轻挽萤7 分钟前
17. C++17新特性-并行算法 (Parallel Algorithms)
java·开发语言·c++
StockTV19 分钟前
SpringBoot对接黄金白银期货数据API
java·spring boot·后端
hsjcjh30 分钟前
窗口函数-详细讲解分析
java·服务器·前端
东北甜妹1 小时前
Redis Cluster 操作命令
java·开发语言
消失的旧时光-19431 小时前
Spring Boot 核心机制之 @Conditional:从原理到实战(一次讲透)
java·spring boot·后端
石榴树下的七彩鱼1 小时前
智能抠图 API 接入实战:3 行代码实现图片自动去背景(Python / Java / PHP / JS)
java·图像处理·人工智能·python·php·api·抠图
知兀1 小时前
【Result类】(使用/不使用<T> data的情况);自带静态方法、纯数据类;
java·开发语言
Seven971 小时前
【从0到1构建一个ClaudeAgent】协作-自主Agent
java
洋不写bug1 小时前
Java线程(三):线程执行顺序问题、可重入锁、加锁操作解析,死锁解决
java·开发语言