文件压缩下载

 @GetMapping("/down")
    public void down(HttpServletRequest request, HttpServletResponse response){
        try {
            response.reset();
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Content-Disposition", "attachment; filename=html580.zip");
            response.setContentType("application/x-zip-compressed");
            response.setContentType("application/octet-stream;charset=ISO-8859-1");

            ServletOutputStream fileOut = response.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(fileOut);
            String pathname="E:\\excel";
            File inputFolder = new File(pathname);
            File[] files= inputFolder.listFiles();
            for (File file:files) {
                if (file.exists()) {
                    ZipEntry ze = new ZipEntry(file.getName());
                    ze.setSize(file.length());
                    ze.setTime(file.lastModified());
                    out.putNextEntry(ze);
                    InputStream stream = new FileInputStream(file);
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    stream.close();
                }
            }
            out.close();
            fileOut.flush();
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)