@PostMapping("/importUserTable")
@Anonymous
public AjaxResult importUserTable(@RequestParam("file") MultipartFile file) throws IOException {
return AjaxResult.success(bidService.importUserTable(file));
}
解压zip文件并存到项目的相对路径 方便文件的上传之后 直接访问静态资源
@Override
public String importUserTable(MultipartFile zipFile) {
//检查文件是否为空
Optional.ofNullable(zipFile).orElseThrow(() -> new IllegalArgumentException("上传的文件为空"));
// 检查文件扩展名是否为.zip
if (!zipFile.getOriginalFilename().toLowerCase().endsWith(ZIP_FILE_EXTENSION)) {
throw new IllegalArgumentException("上传的文件必须是.zip格式");
}
// 解压ZIP文件
String relativePath = "profile"; // 相对于项目根目录的路径
Path uploadDirPath = Paths.get(relativePath);
unzip(zipFile, uploadDirPath.toString());
log.info("解压成功到:" + uploadDirPath);
// 上传解压后的文件
File destDir = new File(uploadDirPath.toString());
uploadUnzippedFiles(destDir);
return "导入成功";
}
// 定义一个方法来解压ZIP文件
public void unzip(MultipartFile zipFile, String destDirPath) {
try {
// 创建目标目录
// 使用当前日期创建目录结构
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String currentDateStr = dateFormat.format(new Date());
String uploadPath = Paths.get(destDirPath, currentDateStr).toString();
File destDir = new File(uploadPath);
if (!destDir.exists()) {
destDir.mkdir();
}
// 使用 Apache Commons Compress 来解压 ZIP 文件
try (InputStream is = zipFile.getInputStream();
ZipArchiveInputStream zis = new ZipArchiveInputStream(is)) {
ZipArchiveEntry entry = zis.getNextZipEntry();
while (entry != null) {
File filePath = new File(destDir, entry.getName());
if (entry.isDirectory()) {
filePath.mkdirs();
} else {
File parent = filePath.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (OutputStream outputStream = new FileOutputStream(filePath)) {
IOUtils.copy(zis, outputStream);
}
}
String fileName = entry.getName();
String[] parts = fileName.split("-");
if (parts.length == 4) {
.....
//保存到数据库中
saveToDatabase();
}
entry = zis.getNextZipEntry();
}
}
} catch (IOException e) {
log.error("IO error: " + e.getMessage());
// 处理其他可能的I/O错误
}
}
// 定义一个方法来上传解压后的文件
public void uploadUnzippedFiles(File destDir) {
// 这里只是一个占位符,你需要实现遍历目录并上传文件的逻辑
File[] files = destDir.listFiles();
if (files != null) {
for (File file : files) {
if (!file.isDirectory()) {
// 这里上传每个文件
log.info("文件上传成功:" + file.getAbsolutePath());
}
}
}
}