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/";
  }
相关推荐
liuyao_xianhui3 分钟前
动态规划_简单多dp问题_打家劫舍_打家劫舍2_C++
java·开发语言·c++·算法·动态规划
小鸡脚来咯7 分钟前
SQL表连接
java·开发语言·数据库
QC班长14 分钟前
如何进行接口性能优化?
java·linux·性能优化·重构·系统架构
聆风吟º15 分钟前
直击复杂 SQL 瓶颈:金仓基于代价的连接条件下推技术落地
java·数据库·sql·kingbasees
兆子龙1 小时前
ahooks useMemoizedFn:解决 useCallback 的依赖地狱
java·javascript
曹牧6 小时前
BeanUtils.copyProperties‌
java
QWQ___qwq6 小时前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊7 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码8 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
阿珍爱上了阿强,在一个有星星的夜晚9 小时前
node后端页面性能监测分析
java·学习方法