Java批量壓縮下載

來源:互聯網
上載者:User

標籤:output   catch   getpath   bst   split   ipa   pre   傳輸   proc   

最近做了一些有關批量壓縮下載的功能,網上也找了一些資源,但都不是太全面,所以自己整理一份,已備不時之需。

直接上代碼:

  // 擷取項目路徑
  private static String WEBCLASS_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();
  // 擷取webinf路徑
  private static String WEBINF_PATH = WEBCLASS_PATH.substring(0, WEBCLASS_PATH.lastIndexOf("classes"));
  // 擷取upload路徑
  private static String UPLOAD_PATH = WEBINF_PATH.substring(0, WEBINF_PATH.lastIndexOf("WEB-INF")) + "upload/";

 public void downloadAllFiles(HttpServletRequest request, HttpServletResponse response) {        // 擷取要下載的檔案對應的資訊ID-選中檔案ID拼接的字串        String lessionIdStr = request.getParameter("fileIds");        // 第一個檔案的檔案名稱        String firstFileName = "";        List<UploadFileInfo> downLoadFiles = new LinkedList<UploadFileInfo>();        if (StringUtil.isNotEmpty(lessionIdStr)) {            int end = lessionIdStr.lastIndexOf(",");            if (end > 0) {                if (end == lessionIdStr.length() - 1) {                    lessionIdStr = lessionIdStr.substring(0, end);                }                String[] ids = lessionIdStr.split(",");                for (int i = 0; i < ids.length; i++) {                    // 迴圈擷取每一個檔案資訊                    UploadFileInfo fileInfo = uploadFileInfoService.selectByPrimaryKey(ids[i]);                    if (fileInfo != null) {                        downLoadFiles.add(fileInfo);                    }                    if (i == 0) {                        firstFileName = fileInfo.getFileName().substring(0, fileInfo.getFileName().lastIndexOf("."));                    }                }            }else {                // 迴圈擷取每一個檔案資訊                UploadFileInfo fileInfo = uploadFileInfoService.selectByPrimaryKey(lessionIdStr);                if (fileInfo != null) {                    downLoadFiles.add(fileInfo);                }                firstFileName = fileInfo.getFileName().substring(0, fileInfo.getFileName().lastIndexOf("."));            }        }                // 有資料可以下載         if (downLoadFiles.size() != 0) {            // 進行預先處理             preProcess(firstFileName, response);            // 壓縮處理            writeZip(downLoadFiles);            // 下載檔案            downFile(response);            // 刪除臨時壓縮檔              afterProcess();        }    }        // 壓縮檔輸出資料流    private ZipOutputStream out;    // 臨時壓縮檔儲存路徑    private String filePath;        /**     * 描述: 預先處理     * 參數: @param firseFileName 批量下載的第一個檔案名稱     * 參數: @param response          */    private void preProcess(String firseFileName, HttpServletResponse response) {        // 壓縮檔名稱        String zipName = "【批量下載】" + firseFileName + "等.zip";        filePath = UPLOAD_PATH + zipName;        try {            // 初始化壓縮檔輸出資料流            out = new ZipOutputStream(new FileOutputStream(filePath));            // 清空輸出資料流(在迅雷下載不會出現一長竄)            response.reset();            //設定回應標頭和用戶端儲存檔案名稱            response.setCharacterEncoding("utf-8");            response.setContentType("multipart/form-data");            // !!!new String(zipName.getBytes("GBK"), "8859_1") 如果檔案包含中文,必須進行轉換,否則下載後的檔案名稱是亂碼格式的            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(zipName.getBytes("GBK"), "8859_1"));        } catch (IOException e) {            e.printStackTrace();        }    }        /**     * 描述: 壓縮處理     * 參數: @param downloadFiles 批量下載的檔案資料集合     */    private void writeZip(List<UploadFileInfo> downloadFiles) {        byte[] buf = new byte[2048];        int len = 0;        try {            for (UploadFileInfo fileInfo : downloadFiles) {                // 擷取上傳檔案                File file = new File(UPLOAD_PATH.substring(0, UPLOAD_PATH.lastIndexOf("upload")) + fileInfo.getFilePath());                if (!file.isFile()) {                    continue;                }                    // 設定編碼                    out.setEncoding(System.getProperty("sun.jnu.encoding"));                    // 設定壓縮檔名稱                    ZipEntry ze = new ZipEntry(fileInfo.getFileName());                    // 加入到輸出資料流中                    out.putNextEntry(ze);                    // 對源檔案進行讀取並輸出                    FileInputStream fis = new FileInputStream(file);                    while ((len = fis.read(buf)) != -1) {                        out.write(buf, 0, len);                    }                    // 重新整理(必須要有)                    out.flush();                    out.closeEntry();                    fis.close();            }            if (out != null) {                out.close();            }        } catch (IOException e) {            e.printStackTrace();        }      }        /**     * 描述: 下載臨時壓縮檔     * 參數: @param response     */    private void downFile(HttpServletResponse response) {        try {            File file = new File(filePath);            if (file.exists()) {                InputStream ins = new FileInputStream(filePath);                // 放到緩衝流裡面                BufferedInputStream bins = new BufferedInputStream(ins);                // 擷取檔案輸出IO流                OutputStream outs = response.getOutputStream();                  BufferedOutputStream bouts = new BufferedOutputStream(outs);                int bytesRead = 0;                byte[] buffer = new byte[1024];                // 開始向網路傳輸檔案流                   while ((bytesRead = bins.read(buffer)) != -1) {                    bouts.write(buffer, 0, bytesRead);                }                // 這裡一定要調用flush()方法                 bouts.flush();                 ins.close();                bins.close();                outs.close();                bouts.close();            }        } catch (IOException e) {               logger.error("檔案下載出錯", e);        }       }        /**     * 描述: 刪除臨時壓縮檔     */    private void afterProcess() {        // 刪除源檔案        File tempZip=new File(filePath);        if(tempZip.exists()) {            tempZip.delete();        }    }    

Java批量壓縮下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.