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/";
  }
相关推荐
珹洺2 分钟前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
SHUIPING_YANG9 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼22 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、27 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
墨染点香40 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 小时前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
风象南1 小时前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山1 小时前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记