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/";
  }
相关推荐
豆沙沙包?8 分钟前
2025年--Lc201- 378. 有序矩阵中第 K 小的元素(排序)--Java版
java·线性代数·矩阵
华仔啊10 分钟前
3 分钟让你彻底搞懂 Spring 观察者和发布者模式的本质区别
java·后端
没有bug.的程序员11 分钟前
服务治理与 API 网关:微服务流量管理的艺术
java·分布式·微服务·架构·wpf
宠友信息13 分钟前
java微服务驱动的社区平台:友猫社区的功能模块与实现逻辑
java·开发语言·微服务
Full Stack Developme1 小时前
jdk.random 包详解
java·开发语言·python
懒羊羊不懒@1 小时前
Java基础入门
java·开发语言
程序员小假2 小时前
我们来说一说 Redisson 的原理
java·后端
chirrupy_hamal2 小时前
网络编程 - TCP 篇
java
notillusion2 小时前
KWW#71843
java·php·程序优化