以下是用Java代码接收zip文件并解压:
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
// 获取上传的zip文件流
InputStream inputStream = file.getInputStream();
// 创建ZipArchiveInputStream对象
ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(inputStream);
// 创建解压后的文件目录
File destDir = new File("/Users/dest/");
if (!destDir.exists()) {
destDir.mkdir();
}
// 循环遍历压缩文件中的所有文件
ArchiveEntry archiveEntry;
while ((archiveEntry = zipInputStream.getNextEntry()) != null) {
String entryName = archiveEntry.getName();
String[] entryNameParts = entryName.split("/");
String fileName = entryNameParts[entryNameParts.length - 1];
File entryFile = new File(destDir + "/" + fileName);
// 如果是文件夹,就创建文件夹
if (entryName.endsWith("/")) {
entryFile.mkdir();
} else {
// 创建文件输出流
OutputStream outputStream = new FileOutputStream(entryFile);
// 将压缩文件解压到指定文件
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
// 关闭文件输出流
outputStream.close();
}
}
// 关闭ZipInputStream
zipInputStream.close();
return "success";
}
}
该代码使用了Spring框架,接收上传的zip文件,并将其解压到指定目录。其中利用了Apache Commons Compress库实现高效解压。