Jfinal下載過程中進行檔案壓縮
阿新 • • 發佈:2021-10-29
下載zip包有兩種方式,一種是先壓縮好要下載的檔案放在伺服器,點下載時直接下載到本地。但這會出現一個問題,那就是如果要壓縮的檔案過大,會導致頁面卡頓,使用者體驗極差。所以使用在下載過程中動態的對要下載的檔案進行壓縮是一種極好的解決方案。
以下為部分程式碼
/** * * Description: 批量下載作業 * @author willem * @date 2021/10/26 */ public void downloadBatchWork(){ JSONObject person = this.getPersonFromCookie();//教師名 下載時檔名可用 String personName = person.getString("person_name"); String homeWorkIds = getPara("homeWork_ids"); if (StringUtil.isEmpty(homeWorkIds)){ renderJson(this.getJsonResult(false,"homeWork_ids引數不能為空")); return; } SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); HttpServletResponse response = getResponse(); response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); String name = personName +" " + dateFormat.format(new Date()) + ".zip"; String agent= getRequest().getHeader("USER-AGENT"); try { if (agent.contains("MSIE") || agent.contains("Trident")){ name = URLEncoder.encode(name,"utf-8"); }else { name = new String(name.getBytes("utf-8"),"ISO-8859-1"); } }catch (Exception e){ e.printStackTrace(); } response.setHeader("Content-Disposition","attachment;fileName=\"" + name + "\""); List<String[]> result = BoxHomeWorkModel.dao.downloadBatchWork(homeWorkIds); //設定壓縮流,直接寫入responder,實現邊壓縮邊下載 ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); //設定壓縮方法 zipOutputStream.setMethod(ZipOutputStream.DEFLATED); }catch (Exception e){ e.printStackTrace(); } DataOutputStream outputStream = null; try { for (int i = 0; i < result.size(); ++i){ String[] strings = result.get(i); File file = new File(strings[1]); zipOutputStream.putNextEntry(new ZipEntry(strings[0])); outputStream = new DataOutputStream(zipOutputStream); InputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[100]; int length = 0; while ((length = inputStream.read(bytes)) != -1){ outputStream.write(bytes,0,length); } inputStream.close(); zipOutputStream.closeEntry(); } }catch (Exception e){ e.printStackTrace(); }finally { if (outputStream != null){ try { outputStream.flush(); outputStream.close(); zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } renderJson(this.getJsonResult(true,"下載成功")); }
下載過程,因為是動態壓縮檔案導致沒辦法先計算出壓縮後的檔案大小,沒辦法顯示下載進度。但我認為這種方法比第一種對使用者的體驗會更好。