java多文件压缩zip下载_linux压缩文件夹命令

Java (3) 2024-06-09 11:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
java多文件压缩zip下载_linux压缩文件夹命令,希望能够帮助你!!!。

最近遇到一个需求,要求设计批量下载功能,即点击按钮即可将勾选的文件全部打包成压缩包,批量下载下来。

页面如下,勾选对应的复选框,点击批量下载按钮,即可将复选框对应的附件批量压缩成一个zip压缩包,然后浏览器弹框下载。

java多文件压缩zip下载_linux压缩文件夹命令_https://bianchenghao6.com/blog_Java_第1张

前端

// 批量下载 $("#downloadBtn").click(function () { // 获取复选选框对应的ID var ids = getIds(); if (ids == "") { top.layer.msg("请选择要下载的文件!"); return false; } else { window.location.href = "${basePath}/abc/defg/fileOut?ids="+ids; } });

后端

// 批量下载文件 @GetMapping("security/standardLibrary/fileOut") public void fileOut(Integer[] ids){ // 根据ids获取对应的文件名和路径,多个用逗号隔开 Map<String, String> file = fileService.queryFileListById(ids); // 从查询结果中将文件名通过“,”截取出来,形成数组 String[] fileNames = file.get("fileName").split(","); // 从查询结果中将文件路径通过“,”截取出来,形成数组 String[] fileUrls = file.get("fileUrl").split(","); // 对文件流进行压缩操作 ZipOutputStream zos = null; // 读取文件流 BufferedInputStream br = null; try { // 文件的名称 String downloadFilename = "批量文件.zip"; response.reset(); // 设置格式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFilename, "UTF-8")); // 初始化压缩流 zos = new ZipOutputStream(response.getOutputStream()); // 循环下载文件并进行压缩 for (int i = 0; i < fileNames.length; i++) { // 设置压缩文件名称 zos.putNextEntry(new ZipEntry(fileNames[i])); try{ // 获取原文件流,不存在则继续操作 br = new BufferedInputStream(new FileInputStream(fileUrls[i])); }catch (FileNotFoundException e1){ e1.getMessage(); log.error("文件下载错误!文件路径:"+fileUrls[i]); // 当前文件下载错误则跳过继续下载下一个文件 continue; } // 按字节依次读取文件并写入压缩流 byte[] buffer = new byte[1024]; int r = 0; while ((r = br.read(buffer)) != -1) { zos.write(buffer, 0, r); } } // 输出压缩文件流 zos.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { // 关闭压缩流和文件流 if(zos != null){ zos.close(); } if (br != null){ br.close(); } } catch (Exception e) { e.printStackTrace(); } } }

 

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

发表回复