文件批量压缩下载,需要将选中的多个文件打成一个压缩包进行下载,是通过返回文件流给前端的方式进行下载的
//准备要下载的文件信息
ArrayList<Map<String, String>> mapList = new ArrayList<>(); //workFiles:需要下载的文件集合 for (WorkFile workFile : workFiles) { HashMap<String, String> map = new HashMap<>(); String name = workFile.getFileName();//文件名 String path = workFile.getPath;//文件的绝对路径 map.put("fileName",name); map.put("filePath",path); mapList.add(Map); }
//压缩包的生成下载
String zipName = "PFCL" + System.currentTimeMillis() +".zip";//压缩包名 String zipPath = "xxxx";//临时压缩包存放路径 compress(mapList,zipPath,false);//将文件压缩成一个压缩包,并存放在指定路径 File zipFile = new File(zipPath); downloadZip(response,zipName,zipFile);//将压缩包通过文件流方式返回下载
//下载后删除临时压缩包
delZipFile("xxxx");//临时压缩包所在的位置
//上面需要用到的方法compress、downloadZip、delZipFile,可以将这三个方法放到一个工具类中方便调用
public void compress(List<Map<String, String>> filePaths, String zipFilePath, Boolean keepDirStructure) { byte[] buf = new byte[1024]; File zipFile = new File(zipFilePath); try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); for (int i = 0; i < filePaths.size(); i++) { String relativePath = filePaths.get(i).get("filePath"); String relativeName = filePaths.get(i).get("fileName"); if (StringUtils.isEmpty(relativePath)) { continue; } File sourceFile = new File(relativePath); if (sourceFile == null || !sourceFile.exists()) { continue; } FileInputStream fis = new FileInputStream(sourceFile); if (keepDirStructure != null && keepDirStructure) { zos.putNextEntry(new ZipEntry(relativePath)); } else { zos.putNextEntry(new ZipEntry(i + "_" + relativeName)); } int len; while ((len = fis.read(buf)) > 0) { zos.write(buf, 0, len); } zos.closeEntry(); // zos.close(); } zos.close(); if (!zipFile.exists()) { zipFile.createNewFile(); } } catch (Exception e) { e.printStackTrace(); } }
public void downloadZip(HttpServletResponse response, String zipName, File zipFile) { //下载文件 try { response.setCharacterEncoding("utf-8"); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;FileName=" + zipName); ServletOutputStream out = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(zipFile); while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); out.flush(); } out.close(); fis.close(); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }
public void delZipFile(String zipDirectoryPath){ File file=new File(zipDirectoryPath); if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { if (f.getName().endsWith(".zip")) { if(f.delete()) { log.trace("zip文件删除成功"); }else{ log.warn("zip文件删除失败"); } } } } }