maven jar引用
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
主要实现代码(filePathList 为要下载的文件路径集合)
List<Map> fileList = new ArrayList<>(); try { for (int i = 0; i < filePathList .size(); i++) { String pdfPath = filePathList[i]; logger.info("---> 任务的pdf路径信息:{}", pdfPath); if (StringUtils.isNotEmpty(pdfPath)) { String fullPath = fileConfig.getPdfPath() + "/" + pdfPath; // 创建文件对象 File file = new File(fullPath); // 转换成字节 byte[] bytes = new byte[0]; bytes = FileUtils.readFileToByteArray(file); // 存入Map Map map = new HashMap(); String fileName = pdfPath.split("/")[1]; logger.info("===== 文件名:{}", fileName); map.put("fileName", fileName); map.put("outByte", bytes); fileList.add(map); } } } catch (IOException e) { log.error("===== 文件读取失败"); throw new RuntimeException(e); } String zipName = System.currentTimeMillis()+"_"+getRandom(4); //自定义压缩报名 httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\""); //设置响应类型 httpServletResponse.setContentType("application/octet-stream; charset=UTF-8"); try (ZipOutputStream zipOutputStream = new ZipOutputStream(httpServletResponse.getOutputStream())) { // 创建 ZipEntry 对象 for (Map mapNow : fileList) { ZipEntry zipEntry = new ZipEntry((String) mapNow.get("fileName")); zipOutputStream.putNextEntry(zipEntry); zipOutputStream.write((byte[]) mapNow.get("outByte")); } } catch (IOException exception) { exception.printStackTrace(); }