有時候在系統中需要一次性下載多個檔案,但逐個下載檔案比較麻煩,這時候,最好的解決辦法是將所有檔案打包成一個壓縮檔案,然后下載這個壓縮檔案,這樣就可以一次性獲取所有所需的檔案了,
下面是一個名為CompressUtil的工具類的代碼,它提供了一些方法來處理檔案壓縮和下載操作:
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* @author fhey
* @date 2023-05-11 20:48:28
* @description: 壓縮工具類
*/
public class CompressUtil {
private static final Logger logger = LoggerFactory.getLogger(CompressUtil.class);
/**
* 將檔案打包到zip并創建檔案
*
* @param sourceFilePath
* @param zipFilePath
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath) throws IOException {
createLocalCompressFile(sourceFilePath, zipFilePath, null);
}
/**
* 將檔案打包到zip并創建檔案
*
* @param sourceFilePath
* @param zipFilePath
* @param zipName
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath, String zipName) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
if(StringUtils.isBlank(zipName)){
zipName = sourceFile.getName();
}
File zipFile = createNewFile(zipFilePath + File.separator + zipName + ".zip");
try (FileOutputStream fileOutputStream = new FileOutputStream(zipFile)) {
compressFile(sourceFile, fileOutputStream);
}
}
/**
* 獲取壓縮檔案流
*
* @param sourceFilePath
* @return ByteArrayOutputStream
* @throws IOException
*/
public static OutputStream compressFile(String sourceFilePath, OutputStream outputStream) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
return compressFile(sourceFile, outputStream);
}
/**
* 獲取壓縮檔案流
*
* @param sourceFile
* @return ByteArrayOutputStream
* @throws IOException
*/
private static OutputStream compressFile(File sourceFile, OutputStream outputStream) throws IOException {
try (CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)) {
doCompressFile(sourceFile, zipOutputStream, StringUtils.EMPTY);
return outputStream;
}
}
/**
* 處理目錄下的檔案
*
* @param sourceFile
* @param zipOutputStream
* @param zipFilePath
* @throws IOException
*/
private static void doCompressFile(File sourceFile, ZipOutputStream zipOutputStream, String zipFilePath) throws IOException {
// 如果檔案是隱藏的,不進行壓縮
if (sourceFile.isHidden()) {
return;
}
if (sourceFile.isDirectory()) {//如果是檔案夾
handDirectory(sourceFile, zipOutputStream, zipFilePath);
} else {//如果是檔案就添加到壓縮包中
try (FileInputStream fileInputStream = new FileInputStream(sourceFile)) {
//String fileName = zipFilePath + File.separator + sourceFile.getName();
String fileName = zipFilePath + sourceFile.getName();
addCompressFile(fileInputStream, fileName, zipOutputStream);
//String fileName = zipFilePath.replace("\\", "/") + "/" + sourceFile.getName();
//addCompressFile(fileInputStream, fileName, zipOutputStream);
}
}
}
/**
* 處理檔案夾
*
* @param dir 檔案夾
* @param zipOut 壓縮包輸出流
* @param zipFilePath 壓縮包中的檔案夾路徑
* @throws IOException
*/
private static void handDirectory(File dir, ZipOutputStream zipOut, String zipFilePath) throws IOException {
File[] files = dir.listFiles();
if (ArrayUtils.isEmpty(files)) {
ZipEntry zipEntry = new ZipEntry(zipFilePath + dir.getName() + File.separator);
zipOut.putNextEntry(zipEntry);
zipOut.closeEntry();
return;
}
for (File file : files) {
doCompressFile(file, zipOut, zipFilePath + dir.getName() + File.separator);
}
}
/**
* 獲取壓縮檔案流
*
* @param documentList 需要壓縮的檔案集合
* @return ByteArrayOutputStream
*/
public static OutputStream compressFile(List<FileInfo> documentList, OutputStream outputStream) {
Map<String, List<FileInfo>> documentMap = new HashMap<>();
documentMap.put("", documentList);
return compressFile(documentMap, outputStream);
}
/**
* 將檔案打包到zip
*
* @param documentMap 需要下載的附件集合 map的key對應zip里的檔案夾名
* @return ByteArrayOutputStream
*/
public static OutputStream compressFile(Map<String, List<FileInfo>> documentMap, OutputStream outputStream) {
CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream);
try {
for (Map.Entry<String, List<FileInfo>> documentListEntry : documentMap.entrySet()) {
String dirName = documentMap.size() > 1 ? documentListEntry.getKey() : "";
Map<String, Integer> fileNameToLen = new HashMap<>();//記錄單個合同號檔案夾下每個檔案名稱出現的次數(對重復檔案名重命名)
for (FileInfo document : documentListEntry.getValue()) {
try {
//防止單個檔案夾下檔案名重復 對重復的檔案進行重命名
String documentName = document.getFileName();
if (fileNameToLen.get(documentName) == null) {
fileNameToLen.put(documentName, 1);
} else {
int fileLen = fileNameToLen.get(documentName) + 1;
fileNameToLen.put(documentName, fileLen);
documentName = documentName + "(" + fileLen + ")";
}
String fileName = documentName + "." + document.getSuffix();
if (StringUtils.isNotBlank(dirName)) {
fileName = dirName + File.separator + fileName;
}
addCompressFile(document.getFileInputStream(), fileName, zipOutputStream);
} catch (Exception e) {
logger.info("filesToZip exception :", e);
}
}
}
} catch (Exception e) {
logger.error("filesToZip exception:" + e.getMessage(), e);
}
return outputStream;
}
/**
* 將單個檔案寫入檔案壓縮包
*
* @param inputStream 檔案輸入流
* @param fileName 檔案在壓縮包中的相對全路徑
* @param zipOutputStream 壓縮包輸出流
*/
private static void addCompressFile(InputStream inputStream, String fileName, ZipOutputStream zipOutputStream) {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = bufferedInputStream.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
//System.out.println("map size, value is " + RamUsageEstimator.sizeOf(zipOutputStream));
} catch (Exception e) {
logger.info("addFileToZip exception:", e);
throw new RuntimeException(e);
}
}
/**
* 通過網路請求下載zip
*
* @param sourceFilePath 需要壓縮的檔案路徑
* @param response HttpServletResponse
* @param zipName 壓縮包名稱
* @throws IOException
*/
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response, String zipName) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
if(StringUtils.isBlank(zipName)){
zipName = sourceFile.getName();
}
try (ServletOutputStream servletOutputStream = response.getOutputStream()){
CompressUtil.compressFile(sourceFile, servletOutputStream);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
servletOutputStream.flush();
}
}
public static void httpDownloadCompressFileOld(String sourceFilePath, HttpServletResponse response, String zipName) throws IOException {
try (ServletOutputStream servletOutputStream = response.getOutputStream()){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] zipBytes = byteArrayOutputStream.toByteArray();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
response.setContentLength(zipBytes.length);
servletOutputStream.write(zipBytes);
servletOutputStream.flush();
}
}
/**
* 通過網路請求下載zip
*
* @param sourceFilePath 需要壓縮的檔案路徑
* @param response HttpServletResponse
* @throws IOException
*/
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response) throws IOException {
httpDownloadCompressFile(sourceFilePath, response, null);
}
/**
* 檢查檔案名是否已經存在,如果存在,就在檔案名后面加上“(1)”,如果檔案名“(1)”也存在,則改為“(2)”,以此類推,如果檔案名不存在,就直接創建一個新檔案,
*
* @param filename 檔案名
* @return File
*/
public static File createNewFile(String filename) {
File file = new File(filename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
String base = filename.substring(0, filename.lastIndexOf("."));
String ext = filename.substring(filename.lastIndexOf("."));
int i = 1;
while (true) {
String newFilename = base + "(" + i + ")" + ext;
file = new File(newFilename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
i++;
}
}
return file;
}
}
FileInfo類代碼:
/**
* @author fhey
* @date 2023-05-11 21:01:26
* @description: TODO
*/
@Data
public class FileInfo {
private InputStream fileInputStream;
private String suffix;
private String fileName;
private boolean isDirectory;
}
測驗壓縮并在本地生成檔案:
public static void main(String[] args) throws Exception {
//在本地創建壓縮檔案
CompressUtil.createLocalCompressFile("D:\\書籍\\電子書\\醫書", "D:\\test");
}
壓縮并在本地生成檔案驗證結果:

壓縮檔案并通過http請求下載:
/**
* @author fhey
*/
@RestController
public class TestController {
@GetMapping(value = "https://www.cnblogs.com/testFileToZip")
public void testFileToZip(HttpServletResponse response) throws IOException {
String zipFileName = "myFiles";
String sourceFilePath = "D:\\picture";
CompressUtil.httpDownloadCompressFile(sourceFilePath,response, zipFileName);
}
}
壓縮檔案并通過http請求下載驗證結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/553881.html
標籤:JavaScript
上一篇:JS中的事件監聽
下一篇:返回列表
