本篇文章介绍将通过前端将压缩文件(zip格式)上传后端服务(入参格式为MultipartFile类型)后,转换成MultipartFile集合对象。由于使用ZipFile解压时会出现异常报错,这里使用的是Apache Commons Compress的org.apache.commons.compress.archivers.zip.ZipArchiveInputStream解压库进行解析,需要导入相应的jar包,代码实现如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
/**
* zip文件解压缩
*/
@Component
public class FileUplodUtil {
private static Logger log = LoggerFactory.getLogger(FileUplodUtil.class);
/**
* 解压zip
*/
public static List<MultipartFile> unpackZip(MultipartFile multipartFiles){
String originalFilename = multipartFiles.getOriginalFilename() ;
if (!originalFilename.endsWith(".zip")){
throw new RuntimeException( originalFilename+"文件格式错误请上传.zip");
}
List<MultipartFile> multipartFileList = new ArrayList<>();
ZipArchiveInputStream zipInputStream = null;
BufferedInputStream bufferedInputStream = null;
String zipEntryFile;
try {
zipInputStream = new ZipArchiveInputStream(multipartFiles.getInputStream(),Charset.forName("GBK").toString());
bufferedInputStream = new BufferedInputStream(zipInputStream) ;
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextZipEntry()) != null){
if (zipEntry.isDirectory()) {
continue;
}else{
zipEntryFile = zipEntry.getName();
Assert.notNull(zipEntryFile,"压缩文件中子文件的名字格式不正确");
byte[] bytes = new byte[(int)zipEntry.getSize()];
bufferedInputStream.read(bytes,0,(int)zipEntry.getSize());
InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
String contentType = MediaTypeFactory.getMediaType(zipEntryFile).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
MultipartFile multipartFile = new MockMultipartFile(zipEntryFile, zipEntryFile, contentType, byteArrayInputStream);
multipartFileList.add(multipartFile);
byteArrayInputStream.close();
}
}
} catch ( IOException e){
e.printStackTrace();
}finally {
if (bufferedInputStream!=null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zipInputStream != null) {
try {
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return multipartFileList;
}
}