因为项目需要上传zip格式的压缩包,网上查询了一下,发现很都是对文件名和路径进行操作的,我的需求是是直接对MultipartFile file进行操作,因此记录一下;
代码如下:`
java
@Autowired
private Environment env;
@ApiOperation(value = "通过zip导入", notes = ")
@RequestMapping(method = RequestMethod.POST, path = "/batchAddaddByZip")
public Response batchAddaddcycnByZip(@RequestParam("file" MultipartFile file) {
try {
//对后缀名进行判断
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (!".zip".equalsIgnoreCase(suffixName)) {
return new Response(HttpStatus.INTERNAL_SERVER_ERROR, "fail", "电子表格格式有问题,请上传后缀为zip格式的电子表格!!") ;
}
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
//文件路径
String commonPath = env.getProperty("pople.file.path");
String memoPath = commonPath + "xxyy/";
File tempPath = new File(memoPath);
if (!tempPath.exists()) {
tempPath.mkdir();
}
//生成压缩文件对象
ZipInputStream zipFile = new ZipInputStream(file.getInputStream());
//获取压缩文件
ZipEntry zipEntry;
//通过循环来读取zip中的一个个文件
while ((zipEntry = zipFile.getNextEntry()) != null) {
TbXycnResult xy = new TbXycnResult();
//判断是否是文件夹
if (zipEntry.isDirectory()) {
File files = new File(memoPath + zipEntry.getName());
files.mkdirs();
continue;
}
String name = zipEntry.getName();
if (name.contains("/")) {
//获取不带后缀的文件名
String substring = name.substring(name.lastIndexOf("/") + 1, name.lastIndexOf("."));
System.out.println("substring = " + substring);
} else {
String substring = name.substring(0, name.lastIndexOf("."));
System.out.println("substring = " + substring);
}
SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMddHHmmss");
String date = dfs.format(new Date());
//防止文件名重复
name = date + (int) (Math.random() * 10000) + zipEntry.getName().substring(name.lastIndexOf(".", name.length()));
bis = new BufferedInputStream(zipFile);
//不是文件夹,就是文件
File files = new File(memoPath + zipEntry.getName().substring(0,zipEntry.getName().lastIndexOf("/")+1)+name);
//得到文件的父目录
File parent = files.getParentFile();
//如果文件的父目录没有建立,那么先建立父目录的路径
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(files);
bos = new BufferedOutputStream(fos, 1024);
byte[] buf = new byte[1024];
int len = 0;
//read()是有返回读取字符长度,如果读到文件尾部,则返回-1
while ((len = bis.read(buf, 0, 1024)) != -1) {
fos.write(buf, 0, len);
}
bos.flush();
}
zipFile.close();
bos.close();
bis.close();
return new Response(HttpStatus.OK, "success");
} catch (Exception e) {
logger.error("系统异常:{}", e);
return new Response(HttpStatus.INTERNAL_SERVER_ERROR, "fail", e);
}
}’
亲测可用,如有问题欢迎纠正;