需求:有一个存储文件链接的集合,希望将所有文件进行压缩,之后下载为压缩包。
实现效果
实现:见代码
后端代码
/**
* User: yanjun.hou
* Date: 2024/10/15 13:33
* Description:
*/
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.Cleanup;
import org.apache.commons.collections4.CollectionUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.*;
public class ZipUtil {
public static byte[] zipFiles(List<String> fileList) throws SecurityException {
if (CollectionUtils.isEmpty(fileList)) {
return null;
}
byte[] arr = new byte[0];
try {
@Cleanup
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
@Cleanup
ZipOutputStream zipOut = new ZipOutputStream(outputStream);
for (String url : fileList) {
byte[] fileUrlByte = getFileUrlByte(url);
if (ObjectUtil.isEmpty(fileUrlByte)) {
continue;
}
// 提取文件名部分
String fileName = extractFileNameFromUrl(url);
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.write(fileUrlByte);
}
zipOut.finish();
outputStream.flush();
arr = outputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException("ZipUtil | zipFiles 压缩文件异常");
}
return arr;
}
/**
* 获取文件字节
*
* @param fileUrl
* @return
* @throws Exception
*/
public static byte[] getFileUrlByte(String fileUrl) throws Exception {
if (StringUtils.isEmpty(fileUrl)) {
return null;
}
try {
URL url = new URL(fileUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
InputStream is = url.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int length = 0;
while ((length = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
outputStream.close();
is.close();
return outputStream.toByteArray();
}
} catch (IOException e) {
throw new SecurityException(String.format("文件下载失败, %s", e.getMessage()));
}
return null;
}
/**
* 提取文件名部分
*
* @param url
* @return
*/
private static String extractFileNameFromUrl(String url) {
if (StringUtils.isEmpty(url)) {
return null;
}
int lastSlashIndex = url.lastIndexOf('/');
if (lastSlashIndex == -1) {
return url; // 如果 URL 中没有斜杠,则直接返回 URL
} else {
return url.substring(lastSlashIndex + 1);
}
}
public static void main(String[] args) {
List<String> fileList = new ArrayList<>();
fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000012.pdf");
fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000013.pdf");
fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000014.pdf");
zipFiles(fileList);
}
}
前端代码
export function fileBatchDownload(data) {
return request({
url: '/fileBatchDownload',
method: 'post',
data: data
})
}
import {fileBatchDownload} from '@/api/xxx'
fileBatchDownload(voucherNumberList).then(res => {
var raw = window.atob(res.data);
var uInt8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uInt8Array[i] = raw.charCodeAt(i);
}
const blob = new Blob([uInt8Array], {
type: "application/octet-stream",
});
const link = document.createElement("a");
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download =Date.parse(new Date()) + ".zip";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(error => {
console.error('Error downloading files:', error);
});
}