Java 生成Zip压缩文件,并下载功能

简介: 当文件比较大时,为了提高性能生成 压缩包,再下载提高效率。

1、直接上代码,看注释

public void exportMonthData1(Date dateTo,HttpServletRequest request, HttpServletResponse response) throws BaseBizException {
   
        List<String> fileNameList = new ArrayList<>();

        Date dateFrom =  new Date();
        String systemPath = "xxxxx/xxxxx/";
        Calendar cal = Calendar.getInstance();
        //这里是要获取要压缩的所有文件
        while(dateFrom.compareTo(dateTo) <= 0) {
   
            cal.setTime(dateFrom);
            Integer fromYear = cal.get(Calendar.YEAR);
            Integer fromMonth = cal.get(Calendar.MONTH);
            String dateFile = fromYear + String.format("%02d", fromMonth);
            File patchFile = new File(systemPath + dateFile);
            if(patchFile.exists()) {
   
                File[] listFile = patchFile.listFiles();
                for(File fileTemp : listFile) {
   
                    fileNameList.add(fileTemp.getPath());
                }
            }
            //加一个月
            cal.add(Calendar.MONTH, 1);
            dateFrom = cal.getTime();
        }
        //设置响应头信息
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        //设置压缩包的名字,date为时间戳
        Date date = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyMMddHHmm");
        String dateStr = dateformat.format(date);
        String downloadName = "压缩包" + dateStr + ".zip";

        //返回客户端浏览器的版本号、类型
        String agent = request.getHeader("USER-AGENT");
        try {
   
            //针对IE或者以IE为内核的浏览器:
            if (agent.contains("MSIE") || agent.contains("Trident")) {
   
                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
            } else {
   
                //非IE浏览器的处理:
                downloadName = new String(downloadName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (Exception e) {
   
            //e.printStackTrace();
            logger.error("{}",e);
        }
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
        //先创建一个ZipOutputStream,这里可以是FileOutputStream,还没时间测试
        //
        try(ZipOutputStream zipOs = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))){
   
            for(String fileName : fileNameList) {
   
                File file = new File(fileName);
                //这里的文件名,是压缩包里定义的,显示出来也是按这个目录
                ZipEntry entry = new ZipEntry(file.getName());
                zipOs.putNextEntry(entry);
                //增加文件内容,逐个添加
                try(FileInputStream fis = new FileInputStream(fileName)){
   
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while ((len = fis.read(buf)) != -1) {
   
                        zipOs.write(buf, 0, len);
                    }
                    zipOs.flush();
                    fis.close();
                }
                zipOs.closeEntry();
            }
        } catch (IOException e) {
   
            //e.printStackTrace();
            logger.error("exportMonthData error : {} " ,e.getMessage());
        }
    }
}

2、配上controller和vue前端代码

@RequestMapping(value = "/exportmonthdata")
public void exportMonthData(HttpServletRequest request, HttpServletResponse response) throws IOException {
storagechargesService.exportMonthData( request, response);
}

前端vue的代码:

monthStoragechargeExport(){
   
        var _this = this;
        _this.exportLoad = true; //开启转圈圈
        _this.$axios.post("/xxxxx/xxxxx",_this.monthQuery,{
    responseType: "arraybuffer" }).then((result)=>{
   
          var downloadElement = document.createElement("a");
          var blob = new Blob([result], {
   type: "application/vnd.ms-excel;charset=utf-8" });
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = "none";
          downloadElement.href = href;
          downloadElement.download = "xxxxx.zip"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
          _this.exportLoad = false; //关闭转圈圈
        });
      },
相关文章
|
28天前
|
Java 开发者
Java多线程教程:使用ReentrantLock实现高级锁功能
【4月更文挑战第6天】`ReentrantLock`是Java并发编程中一个强大的同步工具,比`synchronized`提供更丰富功能。它支持可响应性、可中断性、公平性选择及条件变量。通过示例展示了创建、公平性设置、可中断锁定、尝试锁定及条件变量的使用。`ReentrantLock`使线程同步更灵活,适用于高性能应用,但使用需谨慎,理解其原理并恰当使用。
|
2月前
|
运维 监控 JavaScript
JAVA村卫生室、诊所云HIS系统源码 支持医保功能
运维运营分系统 1、系统运维:环境管理、应用管理、菜单管理、接口管理、任务管理、配置管理 2、综合监管:统计监管的医疗机构的综合信息,包括医疗业务量、人员配备量、支付分类占比等。 3、系统运营:机构管理、药品目录管理、用户管理、角色管理、字典管理、模板管理、消息管理、运营配置、售后服务、外部系统。
31 0
|
2天前
|
存储 前端开发 搜索推荐
13:Session机制实现用户登录与注销功能-Java Web
13:Session机制实现用户登录与注销功能-Java Web
13 3
|
2天前
|
缓存 前端开发 Java
15:Servlet 3.0文件上传与下载-Java Web
15:Servlet 3.0文件上传与下载-Java Web
11 5
|
2天前
|
安全 前端开发 Java
10:基于Servlet模拟用户登录功能的实现与解析-Java Web
10:基于Servlet模拟用户登录功能的实现与解析-Java Web
13 3
|
2天前
|
存储 监控 Java
如何在Java中实现等待文件修改后再读取数据的功能?
如何在Java中实现等待文件修改后再读取数据的功能?
6 0
|
4天前
|
分布式计算 DataWorks 监控
DataWorks操作报错合集之DataWorks在调用java sdk的createFile功能时报错com.aliyuncs.exceptions.ClientException: 1201111000 如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
9 1
|
8天前
|
缓存 Java 测试技术
Java多线程实战-实现多线程文件下载,支持断点续传、日志记录等功能
Java多线程实战-实现多线程文件下载,支持断点续传、日志记录等功能
|
9天前
|
Java API
java流式实现chatGPT会话功能
java流式实现chatGPT会话功能
8 1
|
10天前
|
设计模式 JavaScript Java
[设计模式Java实现附plantuml源码~结构型] 扩展系统功能——装饰模式
[设计模式Java实现附plantuml源码~结构型] 扩展系统功能——装饰模式