最近有需求,要求从服务器端下载多个文件,并且下载的同时压缩,上网查了半天没有一个行的,最后还是想出下面的办法,仅供参考
/** * 压缩下载的文件夹 * @param namelist 下载的文件列表 * @param path 下载路径 * @param zipname 压缩文件名称 */ public void zipDownloadFile(HttpServletResponse response,Listnamelist,String path,String zipname){ byte[] buf = new byte[1024]; try { // 本地保存设置 response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipname, sysEncoding)+".zip"); response.setContentType("application/x-zip-compressed"); // 向本地写文件 ServletOutputStream sos=response.getOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(sos)); for (String name : namelist) { ZipEntry entry = new ZipEntry(name); zipOut.putNextEntry(entry); InputStream bis = this.getStream(path, name); if(bis!=null){ int readLen = -1; while ((readLen = bis.read(buf, 0, 1024)) != -1) { zipOut.write(buf, 0, readLen); } bis.close(); } } zipOut.close(); } catch (Exception e) { e.printStackTrace(); } }