前台使用layui官方上传文件例子:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传压缩文件</title>
<link rel="stylesheet" type="text/css" href="../../static/admin/layui/css/layui.css" th:href="@{/static/admin/layui/css/layui.css}">
</head>
<body>
<button type="button" class="layui-btn layui-btn-primary" id="test">
<i class="layui-icon"></i>只允许压缩文件
</button>
<script type="text/javascript" src="../../static/admin/layui/layui.js" th:src="@{/static/admin/layui/layui.js}"></script>
<script type="text/javascript" th:inline="javascript">
var ctxPath = [[${#request.getContextPath()}]];
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
upload.render({ //允许上传的文件后缀
elem : '#test'
,url : ctxPath+'/admin/zip/singleFileUpload?type=' + '1002'
,accept : 'file' //普通文件
,exts : 'zip' //只允许上传压缩文件
,size: 100*1024 //文件大小限制为100MB
,done : function(res) {
console.log(res)
}
});
});
</script>
</body>
</html>
spring接收文件:
/**
* 上传文件
*
* @return
* @date 2018年9月5日
*/
@RequestMapping("/singleFileUpload")
@ResponseBody
public Map<String, Object> singleFileUpload(@RequestParam("file") MultipartFile file) {
Map<String, Object> map = new HashMap<>();
if (file.isEmpty()) {
map.put("code", 0);
map.put("msg", "文件为空");
map.put("data", null);
}
try {
// 获取文件并且保存到指定位置
Map<String, String> src = new HashMap<>();
File newFile = new File(UPLOAD_PATH);
if (!newFile.exists()) {
newFile.mkdirs();
}
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_PATH + file.getOriginalFilename());
Files.write(path, bytes);
src.put("src", path.toString());
map.put("code", 0);
map.put("msg", "上传成功!");
map.put("data", src);
} catch (IOException e) {
map.put("code", 0);
map.put("msg", "保存文件出错!");
map.put("data", null);
e.printStackTrace();
}
return map;
}
解压上传的zip文件到当前文件夹:
private void unZip(String filePath) {
// 获取ZIP压缩文件的目录
String currentPath = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
try {
// 创建ZIP文件并制定编码格式
ZipFile zipFile = new ZipFile(filePath, Charset.forName("GBK"));
for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
InputStream inputStream = zipFile.getInputStream(entry);
File file = new File((currentPath + File.separator + name));
// 判断是否是目录
if (entry.isDirectory()) {
file.mkdirs();
continue;
}
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int read = 0;
while ((read = inputStream.read(b)) > 0) {
fos.write(b, 0, read);
}
// 关闭
inputStream.close();
fos.close();
}
// 关闭
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}