Java实现文件批量下载,打包成zip压缩包

时间:2025-02-16 12:00:33
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * @author XXX * @version 1.0 * @date 2021年10月15日 */ public class Test { /** * 日志输出对象 */ private static Logger logger = LoggerFactory.getLogger(Test.class); /** * 文件路径 举例:D:\data\test\file\ */ @Value("${path}") private String path; /** * 文件下载 * * @param param * @return */ @RequestMapping(value = "/test/", method = RequestMethod.POST) @ResponseBody public void downloadFile(@RequestBody String param,HttpServletRequest request, HttpServletResponse response) { OutputStream os = null; ZipOutputStream zos = null; BufferedInputStream bis = null; FileInputStream in = null; try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode root = objectMapper.readTree(param); if (root != null) { JsonNode dataNode = root.findValue("fileNameList"); List<String> fileNameList = objectMapper.readValue(dataNode.toString(), new TypeReference<List<String>>(){}); // 通过response对象获取OutputStream流 os = response.getOutputStream(); // 获取zip的输出流 zos = new ZipOutputStream(os); // 遍历文件名列表添加进压缩包 for (int i = 0; i < fileNameList.size(); i++) { String fileName = fileNameList.get(i); String filePath = path + fileName; File file = new File(filePath); if (file.exists()) { // 读取文件流 in = new FileInputStream(file); // 创建ZIP实体,并添加进压缩包 ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); // 设置压缩后的文件名 String zipFileName = ""; // 设置Content-Disposition响应头,控制浏览器弹出保存框,若没有此句浏览器会直接打开并显示文件 // 中文名要进行编码,否则客户端能下载但名字会乱码 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8")); // 输入缓冲流 bis = new BufferedInputStream(in, 1024 * 10); // 创建读写缓冲区 byte[] buf = new byte[1024 * 10]; int len = 0; while ((len = bis.read(buf, 0, 1024 * 10)) > 0) { // 使用OutputStream将缓冲区的数据输出到客户端浏览器 zos.write(buf, 0, len); } bis.close(); in.close(); zos.closeEntry(); } } } } catch (Exception e) { logger.error("下载文件异常:" + e.toString()); } finally { try { if(null != bis){ bis.close(); } if(null != in){ in.close(); } if(null != zos){ zos.close(); } if(null != os){ os.close(); } } catch (Exception e2) { logger.error(e2.toString()); } } } }