1. 程式人生 > 實用技巧 >HTML 以壓縮包下載多檔案

HTML 以壓縮包下載多檔案

Html: 利用form表單來發送下載請求
<form id ="submitForm" method="post">
</form>

JS:

var arr=多個檔案的檔名以逗號隔開;
$("#submitForm").attr("action","<%=request.getContextPath()%>/Pe03/toDownLoad?ape505="+arr);
$("#submitForm").submit();

java:

//下載附件
@SystemControllerLog(description="下載附件")
@RequestMapping("/toDownLoad")
@ResponseBody
public void downPrintLodopFile(String [] ape505,HttpServletRequest request, HttpServletResponse response) throws Exception{ //獲得檔案路徑 String realPath = request.getSession().getServletContext().getRealPath("/upload/預警處理模組上傳目錄/"); for(int i=0;i<ape505.length-1;i++){ ape505[i]=realPath+ape505[i]; }
//執行down down(realPath, ape505, request, response); } public void down(String path, String[] files, HttpServletRequest request, HttpServletResponse response) throws Exception { // path 壓縮檔案初始設定 // 拼接zip檔案,之後下載下來的壓縮檔案的名字 String base_name = "附件"; String fileZip = base_name + ".zip"; // 之後用來生成zip檔案
String filePath = path + fileZip; // 建立臨時壓縮檔案 try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); ZipOutputStream zos = new ZipOutputStream(bos); ZipEntry ze = null; // 將所有需要下載的檔案都寫入臨時zip檔案 for (int i = 0; i < files.length-1; i++) { BufferedInputStream bis = new BufferedInputStream( new FileInputStream(files[i])); ze = new ZipEntry( files[i].substring(files[i].lastIndexOf("\\"))); zos.putNextEntry(ze); int s = -1; while ((s = bis.read()) != -1) { zos.write(s); } bis.close(); } zos.flush(); zos.close(); } catch (IOException e) { e.printStackTrace(); } // 以上,臨時壓縮檔案建立完成 // 進行瀏覽器下載 // 獲得瀏覽器代理資訊 String agent = request.getHeader("User-Agent").toUpperCase(); // 判斷瀏覽器代理並分別設定響應給瀏覽器的編碼格式 String finalFileName = null; if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1))) finalFileName = URLEncoder.encode(fileZip, "UTF-8"); else { finalFileName = new String(fileZip.getBytes("UTF-8"), "ISO8859-1"); } // 告知瀏覽器下載檔案,而不是直接開啟,瀏覽器預設為開啟 response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");// 下載檔案的名稱 //輸出到本地 ServletOutputStream servletOutputStream = response.getOutputStream(); DataOutputStream temps = new DataOutputStream(servletOutputStream); // 瀏覽器下載臨時檔案的路徑 DataInputStream in = new DataInputStream(new FileInputStream(filePath)); byte[] b = new byte[2048]; // 之後用來刪除臨時壓縮檔案 File reportZip = new File(filePath); try { while ((in.read(b)) != -1) { temps.write(b); } temps.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (temps != null) { temps.close(); } if (in != null) { in.close(); } // 刪除伺服器本地產生的臨時壓縮檔案 if (reportZip != null){ reportZip.delete(); } servletOutputStream.close(); } }