springmvc上傳zip檔案解析,並獲取每個zipEntry的輸入流
阿新 • • 發佈:2019-01-04
1.解析springmvc上傳zip的工具類:
public class FileUtils { //日誌 private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); /** * 對zip型別的檔案進行解壓 * * @author mmy * @date 2018年1月8日 */ public static List<FileModel> unzip(MultipartFile file) { // 判斷檔案是否為zip檔案 String filename = file.getOriginalFilename(); if (!filename.endsWith("zip")) { LOGGER.info("傳入檔案格式不是zip檔案" + filename); new BusinessException("傳入檔案格式錯誤" + filename); } List<FileModel> fileModelList = new ArrayList<FileModel>(); String zipFileName = null; // 對檔案進行解析 try { ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("GBK")); BufferedInputStream bs = new BufferedInputStream(zipInputStream); ZipEntry zipEntry; byte[] bytes = null; while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 獲取zip包中的每一個zip file entry zipFileName = zipEntry.getName(); Assert.notNull(zipFileName, "壓縮檔案中子檔案的名字格式不正確"); FileModel fileModel = new FileModel(); fileModel.setFileName(zipFileName); bytes = new byte[(int) zipEntry.getSize()]; bs.read(bytes, 0, (int) zipEntry.getSize()); InputStream byteArrayInputStream = new ByteArrayInputStream(bytes); fileModel.setFileInputstream(byteArrayInputStream); fileModelList.add(fileModel); } } catch (Exception e) { LOGGER.error("讀取部署包檔案內容失敗,請確認部署包格式正確:" + zipFileName, e); new BusinessException("讀取部署包檔案內容失敗,請確認部署包格式正確:" + zipFileName); } return fileModelList; } }
2.儲存每個解壓後文件的model
public class FileModel implements Serializable{ private static final long serialVersionUID = 13846812783412684L; String fileName; //解壓後文件的名字 String fileType; //檔案型別 InputStream fileInputstream; //解壓後每個檔案的輸入流 public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileType() { return this.fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public InputStream getFileInputstream() { return this.fileInputstream; } public void setFileInputstream(InputStream fileInputstream) { this.fileInputstream = fileInputstream; } public String toString() { return "FileModel{fileName=\'" + this.fileName + '\'' + ", fileType=\'" + this.fileType + '\'' + ", fileInputstream=" + this.fileInputstream + '}'; } }