java 生成zip文件并浏览器导出

时间:2024-03-07 13:25:53

总结一下,关于Java下载zip文件并导出的方法,浏览器导出。

复制代码
     String downloadName = "下载文件名称.zip";
        downloadName = BrowserCharCodeUtils.browserCharCodeFun(request, downloadName);//下载文件名乱码问题解决
        
        //将文件进行打包下载
        try {
            OutputStream out = response.getOutputStream();
            byte[] data = createZip("/fileStorage/download");//服务器存储地址
            response.reset();
            response.setHeader("Content-Disposition","attachment;fileName="+downloadName);
            response.addHeader("Content-Length", ""+data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
复制代码

 

 

//获取下载zip文件流

复制代码
public byte[] createZip(String srcSource) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //将目标文件打包成zip导出
        File file = new File(srcSource); 
        a(zip,file,"");
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
复制代码

 

复制代码
public void a(ZipOutputStream zip, File file, String dir) throws Exception {
            //如果当前的是文件夹,则进行进一步处理
            if (file.isDirectory()) {
                //得到文件列表信息
                File[] files = file.listFiles();
                //将文件夹添加到下一级打包目录
                zip.putNextEntry(new ZipEntry(dir + "/"));
                dir = dir.length() == 0 ? "" : dir + "/";
                //循环将文件夹中的文件打包
                for (int i = 0; i < files.length; i++) {
                    a(zip, files[i], dir + files[i].getName());         //递归处理
                }
            } else {   //当前的是文件,打包处理
                //文件输入流
               BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
               ZipEntry entry = new ZipEntry(dir);
               zip.putNextEntry(entry);
               zip.write(FileUtils.readFileToByteArray(file));
               IOUtils.closeQuietly(bis);
               zip.flush();
               zip.closeEntry();
            }
    }
复制代码