java文件打包壓縮輸出到瀏覽器下載

java批量下載文件打包壓縮工具類,輸出到瀏覽器下載,可以自己改名。

工具類:

 入參 :文件LIst ;打包後的名字 ;響應到瀏覽器

/**
     * 功能:壓縮多個文件,輸出壓縮後的zip文件流
     *
     * @param srcfile:源文件列表
     * @param zipFileName:壓縮後的文件名
     * @param response:           Http響應
     */
    public void zipFiles(List<File> srcfile, String zipFileName, HttpServletResponse response) throws IOException {
        byte[] buf = new byte[1024];
        // 獲取輸出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            response.reset(); // 重點突出
            // 不同類型的文件對應不同的MIME類型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");

            // ZipOutputStream類:完成文件或文件夾的壓縮
            out = new ZipOutputStream(bos);
            for (int i = 0; i < srcfile.size(); i++) {
                in = new FileInputStream(srcfile.get(i));
                // 給列表中的文件單獨命名
                out.putNextEntry(new ZipEntry(srcfile.get(i).getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            out.close();
            bos.close();
            log.info("壓縮完成.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }

二:調用

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章