一下代码实现的是将多个文件进行压缩,采用的是边压缩边下载的方式
/** * 压缩文件 * @param exportFilePathList * @param response */ public static void downloadPictureZip(List<String> exportFilePathList, HttpServletResponse response) { ZipOutputStream zipos = null; try { zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); zipos.setMethod(ZipOutputStream.DEFLATED);// 设置压缩方法DEFLATED } catch (Exception e) { e.printStackTrace(); } DataOutputStream os = null; // 循环将文件写入压缩流 for (String filePath : exportFilePathList) { File file = new File(filePath); try { // 添加ZipEntry,并ZipEntry中写入文件流 zipos.putNextEntry(new ZipEntry(file.getName())); 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 (Exception e) { e.printStackTrace(); } } // 关闭流 try { os.flush(); os.close(); zipos.close(); } catch (IOException e) { e.printStackTrace(); } }完整的请求流程 :以下是 controller层的
/** * 导出选中图片 * @return */ public void exportSelectedResult(){ String[] strings = docIds.split(","); //要导出的对象集合 List<FeedBackMessage> fbmList=new ArrayList<>(); List<String> exportFilePathList= new ArrayList<>(); String root = PropertyUtil.get("feedbackpicPath"); for(String id:strings){ //根据选中图片的ID 查询输数据库 得到图片的名称 FeedBackMessage feedBack=pictureService.findFeedBackMessageById(Integer.valueOf(id)); fbmList.add(feedBack); } for(FeedBackMessage feedBack :fbmList){ feedBack.setPicPath(root+feedBack.getPicPath()); exportFilePathList.add(feedBack.getPicPath()); } //设置压缩包的名字 //解决不同浏览器压缩包名字含有中文时乱码的问题 String zipName= DateUtil.getCurrentDate("yyyyMMddHHmmss")+".zip"; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename="+ zipName); //导出的工具类 PictureUtil.downloadPictureZip(exportFilePathList,response); }需要注意的是 不需要进行目录压缩的时候,参数传入文件的名称即可 如下图