/**
*
* @apiNote
* @author 嗯呢某
* @since 2024/2/19 17:06
*/
public class CompressFileUtil {
private static final Logger logger = LoggerFactory.getLogger(CompressFileUtil.class);
/**
* @apiNote 导出文件压缩包
* @author 嗯呢某
* @since 2024/2/19
* @param response
* @param fileNameBufMap 文件名与内容的映射,文件在一个文件夹内则使用a/b.txt,标识文件夹a内有b.txt文件
* @param zipName
* @return void
*/
public static void outputZipFile(HttpServletResponse response, Map<String, StringBuffer> fileNameBufMap, String zipName) throws IOException {
logger.info("进行文件压缩包的导出 | zipName = {}", zipName);
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
responseSetProperties(zipName, response);
for (Map.Entry<String, StringBuffer> entry : fileNameBufMap.entrySet()) {
ZipEntry fileEntry = new ZipEntry(entry.getKey());
zipOut.putNextEntry(fileEntry);
zipOut.write(entry.getValue().toString().getBytes(StandardCharsets.UTF_8));
zipOut.closeEntry();
}
zipOut.flush();
zipOut.close();
response.getOutputStream().flush();
}
/**
* 设置Header
*
* @param zipName
* @param response
* @throws UnsupportedEncodingException
*/
private static void responseSetProperties(String zipName, HttpServletResponse response) throws UnsupportedEncodingException {
zipName = URLEncoder.encode(zipName, "UTF-8");
// 设置文件后缀
response.setCharacterEncoding("utf8");
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
}
}
Java实现多文件成zip并实现下载,后端HTTP响应方式
于 2024-02-19 18:16:36 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)