原文地址:https://www.jianshu.com/p/7cabe09ce563
親測有效,很好用!
public void downloadFiles(HttpServletRequest request, HttpServletResponse response, 其他爲獲取下載文件信息的必須參數){ //響應頭的設置 response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); //設置壓縮包的名字 //解決不同瀏覽器壓縮包名字含有中文時亂碼的問題 String downloadName = "我是壓縮包的名字.zip"; String agent = request.getHeader("USER-AGENT"); try { if (agent.contains("MSIE")||agent.contains("Trident")) { downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8"); } else { downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1"); } } catch (Exception e) { e.printStackTrace(); } response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\""); //設置壓縮流:直接寫入response,實現邊壓縮邊下載 ZipOutputStream zipos = null; try { zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); zipos.setMethod(ZipOutputStream.DEFLATED); //設置壓縮方法 } catch (Exception e) { e.printStackTrace(); } //循環將文件寫入壓縮流 DataOutputStream os = null; for(int i = 0; i < 要下載的文件個數; i++ ){ File file = new File(要下載的某個文件的路徑); try { //添加ZipEntry,並ZipEntry中寫入文件流 //這裏,加上i是防止要下載的文件有重名的導致下載失敗 zipos.putNextEntry(new ZipEntry(i + 文件名字)); os = new DataOutputStream(zipos); InputStream is = new FileInputStream(file); byte[] b = new byte[100]; int length = 0; while((length = is.read(b))!= -1){ os.write(b, 0, length); } is.close(); zipos.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } //關閉流 try { os.flush(); os.close(); zipos.close(); } catch (IOException e) { e.printStackTrace(); } }