try { String fileName = courseWare.getTitle(); SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); //设置字符集和文件后缀名 response.setContentType("application/octet-stream"); //兼容问题 String name = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); if (request.getHeader("User-Agent").toUpperCase().indexOf("TRIDENT") > -1 || request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > -1) { name = URLEncoder.encode(fileName, "UTF-8"); } // 设置文件名称 response.setHeader("Content-Disposition", "attachment; filename=" + name + ".zip"); OutputStream out = response.getOutputStream(); // 声明压缩流对象 ZipOutputStream zipOut = new ZipOutputStream(out) ; // 定义文件输入流 int temp = 0; File file; byte[] buffer = new byte[1024 * 8]; Field[] fields = courseWare.getExtendVo().getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String pkAttached = field.get(courseWare.getExtendVo()).toString(); if(pkAttached != null && !"".equals(pkAttached)){ Attached attached = attachedService.query(pkAttached); if(attached != null && attached.getFilePath() != null && !"".equals(attached.getFilePath())){ String docFileName = attached.getFilePath(); docFileName = docFileName.replace(ip,uploadurl); file = new File(docFileName); InputStream input = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(attached.getFileName())); while((temp = input.read(buffer)) > 0) { zipOut.write(buffer, 0, temp); } input.close(); } } } String pkAttached = courseWare.getUrl(); if(pkAttached != null && !"".equals(pkAttached)){ Attached attached = attachedService.query(pkAttached); if(attached != null && attached.getFilePath() != null && !"".equals(attached.getFilePath())){ String docFileName = attached.getFilePath(); docFileName = docFileName.replace(ip,uploadurl); file = new File(docFileName); InputStream input = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(attached.getFileName())); while((temp = input.read(buffer)) > 0) { zipOut.write(buffer, 0, temp); } input.close(); } } zipOut.flush(); zipOut.close(); } catch (Exception e) { e.printStackTrace(); }
获取文件集合并生成zip压缩包进行页面下载
最新推荐文章于 2023-03-11 02:56:05 发布
这段代码主要实现了根据用户请求,将多个文件进行压缩并下载的功能。它首先获取文件名,然后设置日期格式,并通过响应设置内容类型和文件名。接着,针对不同浏览器的兼容性问题,对文件名进行编码。通过ZipOutputStream创建压缩流,遍历并读取每个文件内容,将其写入压缩包中。整个过程中涉及了文件输入流、输出流以及ZipEntry的使用。
摘要由CSDN通过智能技术生成