SpringMVC生成zip并下载

本文介绍了一种使用Java标准库中的zip相关类来压缩和下载日志文件的方法。通过创建一个zip文件将多个日志文件打包,并提供了一个下载功能,允许用户以zip格式下载这些日志。

利用JDK自带的zip相关类,在util目录下。

1、生成zip文件

public String createLog() throws IOException {
        String zipFileName = null;
        String logFolderPath = PathConst.LOG_PATH;
        File[] logFiles = taskLogFolder.listFiles();
        zipFileName =  "log.zip";
        String zipFileNamePath = logFolderPath + "/" + zipFileName;
        File zipFile = new File(zipFileNamePath);
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
        FileInputStream fileInputStream = null;
        byte[] buf = new byte[1024];
        int len = 0;
        if (logFiles != null && logFiles.length > 0) {
            for (File logFile : logFiles) {
                String fileName = logFile.getName();
                if (!fileName.equals(zipFileName)) {
                    fileInputStream = new FileInputStream(logFile);
                    //放入压缩包
                    zipOutputStream.putNextEntry(new ZipEntry(fileName));
                    //读取文件
                    while ((len = fileInputStream.read(buf)) > 0) {
                        zipOutputStream.write(buf, 0, len);
                    }
                    //关闭
                    zipOutputStream.closeEntry();
                    fileInputStream.close();
                }
            }
        }
        zipOutputStream.close();
        return zipFileName;
    }

2、下载zip文件

    public void downloadLog(String zipFileName, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        String zipFilePath = PathConst.LOG_PATH;
        File file = new File(zipFilePath, zipFileName);
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        OutputStream outStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFileName.getBytes("UTF-8"), "ISO-8859-1"));
        outStream.write(buffer);
        outStream.flush();
        outStream.close();
    }

Content-type

内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件。
文件扩展名与 Content-type 的对应关系,参见 http://tool.oschina.net/commons

Content-Disposition

Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 IE 浏览器接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。Content-Disposition 就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值