上傳檔案,解壓zip
阿新 • • 發佈:2019-01-02
前臺使用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(); } }