zip 通过response 下载,不足 多级目录目录的文件只会压缩到一个文件夹中

 @ResponseBody
    @RequestMapping("/szctest1")
    public void zip1(HttpServletResponse response,HttpServletRequest request) throws IOException {
        String path = "D:\\test"; //要压缩的目录
        String zipName = "test.zip";
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename="+zipName+"");
        try (ZipOutputStream zipOs = new ZipOutputStream(response.getOutputStream())) {
            traverseFolder2(path,response,zipOs);
        } catch (IOException ioException) {

        }
    }
    public void traverseFolder2(String path,HttpServletResponse response,ZipOutputStream zipOs) {

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        traverseFolder2(file2.getAbsolutePath(),response,zipOs);
                    } else {
                        String absolutePath = file2.getAbsolutePath();
                        System.out.println("文件:" + absolutePath);

                        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file2))) {
                            zipOs.putNextEntry(new ZipEntry(absolutePath.substring(absolutePath.lastIndexOf("\\")+1)));
                            IOUtils.copy(bis, zipOs);
                            zipOs.closeEntry();
                        } catch (IOException ioException) {

                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

 

posted @ 2021-01-28 16:34  我没有出家  阅读(225)  评论(0编辑  收藏  举报