Java将文件压缩成zip并下载
目录
- Java文件压缩成zip并下载
- 1.实体类
- 2.工具类
- 3.js接收blob
- 4.调用
- Java中多目录文件压缩成zip
- 1.实体类
- 2.工具类
- 3.效果
Java文件压缩成zip并下载
使用jdk自带的zip包下的类来实现压缩
1.实体类
实体类主要是文件名和文件路径(base64字符串),压缩文件路径时可以不使用类里的文件名。
import lombok.Data;
@Data
public class FileInfoDto {
/**文件名*/
private String fileName;
**文件路径或base64字符串*/
private String file;
}
2.工具类
创建和删除文件的方式来辅助压缩,在创建一个zip文件时,每个zipEntry代表zip文件中的一个项,zipEntry的名称在zip文件内必须是唯一的,因为zip文件格式使用这些条目名称作为查找键,来定位和提取存储在zip中的文件。所以名称相同时会抛出异常,我这里在调用前做了处理。
我省略了项目路径的import,使用时导入自己的路径即可。
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author xxx
* @date 2023/10/18 14:43
* @description:
*/
public class BaseZipUtils {
/**
* 使用给定的文件列表创建ZIP文件并将其发送到HTTP响应。
*
* @param response HttpServletResponse
* @param fileList 文件列表
* @param title ZIP文件的标题
* @param type 1-base64压缩,2-url-压缩
*/
public static void downZipFile(HttpServletResponse response, List<FileInfoDto> fileList, String title, Integer type) {
// 获取模板路径,并构建ZIP文件的完整路径。
String tempDirPath = getTemplatePath();
File zipFilePath = new File(tempDirPath, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "_" + title);
try {
if (1 == type) {
// 基于Base64编码的文件创建ZIP文件。
zipFiles(fileList, zipFilePath);
} else {
zipFilesFromURLs(fileList, zipFilePath);
}
// 如果ZIP文件存在,将其发送到HTTP响应。
if (zipFilePath.exists()) {
try (InputStream is = new FileInputStream(zipFilePath);
OutputStream os = response.getOutputStream()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(zipFilePath.getName(), "UTF-8"));
// 从ZIP文件读取内容并写入HTTP响应。
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} finally {
// 删除临时ZIP文件。
Files.deleteIfExists(zipFilePath.toPath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将Base64编码的文件列表压缩为一个ZIP文件。
*
* @param srcFiles 需要压缩的文件列表
* @param zipFile 生成的ZIP文件
*/
public static void zipFiles(List<FileInfoDto> srcFiles, File zipFile) throws IOException {
// 如果ZIP文件不存在,创建它。
if (!zipFile.exists()) {
Files.createFile(zipFile.toPath());
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
for (FileInfoDto fileInfo : srcFiles) {
// 解码文件名。
String fileName = URLDecoder.decode(fileInfo.getFileName(), "UTF-8");
// 创建ZIP条目并添加到ZIP输出流中。
ZipEntry编程客栈 entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
// 将Base64编码的文件内容解码为字节数组。
byte[] fileBytes = Base64.getDecoder().decode(fileInfo.getFile());
// 将字节数组写入ZIP文件。
zos.write(fileBytes);
zos.closeEntry();
}
}
}
/**
* 使用从URL获取的文件列表创建ZIP文件。
*
* @param srcFilesURLs 需要压缩的文件URL列表
* @param zipFile 生成的ZIP文件
*/
public static void zipFilesFromURLs(List<FileInfoDto> srcFilesURLs, File zipFile) throws IOException {
// 如果ZIP文件不存在,创建它。
if (!zipFile.exists()) {
Files.createFile(zipFile.toPath());
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
for (FileInfoDto dto : srcFilesURLs) {
URL url = new URL(dto.getFile());
// 获取文件的文件名。
String fileName = Paths.get(url.getPath()).getFileName().toString();
// 创建ZIP条目并添加到ZIP输出流中。
ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
// 从URL读取文件内容。
try (InputStream is = url.openStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
// 将从URL读取的内容写入ZIP文件。
zos.write(buffer, 0, bytesRead);
}
}
zos.closeEntry();
}
}
}
/**
*js 获取类路径的绝对地址。
*
* @return 类路径的绝对地址
*/
public static String getTemplatePath() {
try {
String realPath = new ClassPathResource("").getURL().getPath();
return URLDecoder.decode(realPath, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3.js接收blob
/**
* 处理Blob响应并触发浏览器下载。
* @param {Object} res - 包含头信息和数据的响应对象。
* @param {string} [name] - 下载文件的可选名称。
* @param {string} [type2] - Blob的可选类型。
*/
export const handleBlob = (res, name, type2) => {
// 从提供的名称或响应头中获取文件名
const fileName = name || (res.headers['content-disposition'] &&
decodeURI(res.headers['content-disposition'])
.split('filename=')[1]);
// 从提供的type2或响应头中获取类型
const type = type2 || res.headers['content-type'];
// 创建Blob对象
const blob = new Blob([res.data], { type });
// 触发浏览器下载
const downloadElement = document.createElement('a');
downloadElement.href = window.URL.createObjectURL(blob);
downloadElement.download = fileName; // 设置下载文件的名称
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
}
4.调用
String title = "测试.zip"; BaseZipUtils.downZipFile(response, fileList, title,1);
调用结果:


Java中多目录文件压缩成zip
将多个文件打包到zip提供给用户下载,抽离出来了一个工具类,支持单文件、多文件、按类型的多文件的压缩和下载。
1.实体类
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @date 2022/5/25 15:11
* @description:
*/
@Data
public class ZipDto implements Serializable {
/**类型名称/子目录名称*/
private String typeName;
/**文件路径*/
private String fileUrl;
/**
* 分类型时,集合有值
* 文件路径集合
*/
private List<String> urlList;
}
2.工具类
主要方法:
- downZipListType: 允许用户按类型将文件列表打包成zip文件进行下载。
- downZipList: 提供批量下载功能,可以将多个文件一起打包成zip文件。
- downZipOne: 为单个文件提供下载功能,虽然是单个文件,但为了保持统一性,仍然会将其打包成zip格式。
删除了项目敏感import,自行导入实体即可。
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @date 2023/10/18 17:32
* @description:
*/
@Slf4j
@UtilityClass
public class CustomOriZipUtils {
private static final String SUFFIX_ZIP = ".zip";
private static final String UNNAMED = "未命名";
/**
* 按类型批量下载。
*/
public static void downZipListType(List<ZipDto> list, String fileName, HttpServletRequest request, HttpServletResponse response) {
try (ZipOutputStream zos = createZipOutputStream(response, request, fileName)) {
for (ZipDto dto : list) {
www.devze.com writeToZipStream(dto.getUrlList(), zos, dto.getTypeName());
}
} catch (Exception e) {
log.error("创建zip文件出错", e);
}
}
/**
* 批量下载。
*/
public static void downZipList(List<ZipDto> list, String fileName, HttpServletRequest request, HttpServletResponse response) {
try (ZipOutputStream zos = createZipOutputStream(response, request,fileName)) {
for (ZipDto dto : list) {
writeToZipStream(Collections.singletonList(dto.getFileUrl()), zos, dto.getTypeName());
}
} catch (Exception e) {
log.error("创建zip文件出错", e);
}
}
/**
* 下载单个记录。
*/
public void downZipOne(ZipDto dto, String fileName, HttpServletRequest request, HttpServletResponse response) {
try (ZipOutputStream zos = createZipOutputStream(response, request,fileName)) {
writeToZipStream(Collections.singletonList(dto.getFileUrl()), zos, dto.getTypeName());
} catch (Exception e) {
log.error("创建zip文件出错", e);
}
}
/**
* 为下载设置响应。
*/
private void setResponse(HttpServletResponse response, HttpServletRequest request,String fileName) throws UnsupportedEncodingException {
if (StrUtil.isAllBlank(fileName)) {
fileName = LocalDate.now() + UNNAMED;
}
if (!fileName.endsWith(SUFFIX_ZIP)) {
fileName += SUFFIX_ZIP;
}
fileName = encodeFileName(request, fileName);
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
respo编程客栈nse.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}
/**
* 将URL写入zip流中。
*/
private static void writeToZipStream(List<String> urls, ZipOutputStream zos, String subDir) {
byte[] buffer = new byte[1024];
for (String url : urls) {
if (StrUtil.isNotBlank(url)) {
try (InputStream is = new URL(url).openStream()) {
String fileName = StrUtil.isAllBlank(subDir) ? getFileName(url) : subDir + "/" + getFileName(url);
zos.putNextEntry(new ZipEntry(fileName));
int length;
while ((length = is.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
} catch (Exception e) {
log.error("将文件 [{}] 写入zip时出错", http://www.devze.comurl, e);
}
}
}
}
/**
* 根据浏览器类型编码文件名。
*/
private static String encodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
String userAgent = request.getHeader("USER-AGENT");
if (userAgent.contains("Firefox")) {
return new String(fileName.getBytes(), "ISO8859-1");
}
return URLEncoder.encode(fileName, "UTF-8");
}
/**
* 创建ZipOutputStream并设置响应头。
*/
private static ZipOutputStream createZipOutputStream(HttpServletResponse response,HttpServletRequest request, String fileName) throws IOException {
setResponse(response, request,fileName);
return new ZipOutputStream(response.getOutputStream());
}
/**
* 从url获取文件名
* @param url
* @return
*/
public String getFileName(String url) {
return url.substring(url.lastIndexOf('/') + 1);
}
3.效果
多目录文件压缩下载:

单文件打包下载:

到此这篇关于Java将文件压缩成zip并下载的文章就介绍到这了,更多相关Java文件压缩内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
加载中,请稍侯......
精彩评论