以流的方式進行壓縮文件


這個工具類知道了已經要壓縮的文件的路徑,然后需要將這個路徑下的文件進行壓縮。

    /**
     * 壓縮下載照片
     *
     * @param picUrl
     * @param response
     * @throws IOException
     */
    public static void downloadPic(List<String> picUrl, HttpServletResponse response) throws IOException, AdminException {
        try {
            String downloadFilename = System.currentTimeMillis() + ".zip";//文件的名稱
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//轉換中文否則可能會產生亂碼
            response.setContentType("application/octet-stream");// 指明response的返回對象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 設置在下載框默認顯示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            String[] files = new String[picUrl.size()];
            picUrl.toArray(files);
            for (int i = 0; i < files.length; i++) {
                String url = files[i];
                zos.putNextEntry(new ZipEntry(downloadFilename + File.separator + i + ".jpg"));
                InputStream fis = new FileInputStream(new File(url));
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
            zos.flush();
            zos.close();
        } catch (UnsupportedEncodingException e) {
            logger.error("不支持當前格式",e);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM