JAVA以压缩包下载多个附件
public void downPrintLodopFile(String [] ape505,HttpServletRequest request, HttpServletResponse response) throws Exception{ //获得文件路径 String realPath = request.getSession().getServletContext().getRealPath("/upload/上传目录"); // 不知道啥问题,在生产环境中得单独加个"/",否则在生产环境中会缺少"/" realPath +="/"; 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(); } }