背景是有一个上传压缩包,然后解析出指定出包名和版本的需求,直接上代码:
接口:
@PostMapping(value = "/upload")
public Map<String,String> upload(@RequestParam("file") MultipartFile file){
try {
File zipFile = new File(FILE_UPLOAD_PATH + file.getOriginalFilename());
file.transferTo(zipFile);
return UploadAndUnzipUtils.getContainerName(zipFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
工具类:
package com.lenovo.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class UploadAndUnzipUtils {
public static Map<String,String> getContainerName(String zipFilePath) throws IOException {
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.getName().equals("Container.xml")) {
Map<String,String> res = new HashMap<>();
InputStream inputStream = zipFile.getInputStream(entry);
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(inputStream);
Element container = document.getDocumentElement();
res.put("name",container.getAttribute("name"));
res.put("version",container.getAttribute("version"));
return res;
}
}
}catch (Exception e){
}
return null;
}
}
如果稍微帮到你了记得点个喜欢点个关注~
网友评论