上機考試系統 commons-fileupload 上傳與下載 && 壓縮為 zip 檔案 && 刪除資料夾下所有內容
阿新 • • 發佈:2018-11-29
在 maven 中使用了 commons-fileupload,使用方法:
(一)上傳
1-1.前端介面
<form action="" enctype="multipart/form-data" class="modifyall" method="post" id="uploadForm"> <input type="file" name="file" id="file" style="display: inline-block" class="po">
<input type="submit" class="layui-btn layui-btn-sm " value="上傳" id="fileUpload">
</form>
1-2.js
function fileUpload() { var URL = root + "/teacher/teacherUpload"; var data = new FormData($('#uploadForm')[0]); $.ajax({ url : URL, type : "post", data : data, async :false, cache : false, processData : false, contentType : false, success : function(data) {
//返回資料型別為 String if (data == "ok") { location.reload(); } if (data == "min") {
//如果檔案大小小於最小上傳值,返回 "min",並將最小值的大小儲存在 session 中,通過<input type="hidden"> 和 id 獲取最小值var min = $("#min").val(); alert("檔案必須大於" + min); location.reload(); } if (data == "max") {
//同最小值 alert("檔案必須小於" + max); location.reload(); } }, error : function(data) { alert("操作失敗"); } }); }
1-3.Controller@ResponseBody @RequestMapping("/teacherUpload")
public String upload(MultipartFile file, HttpServletRequest request, HttpServletRequest reponse) throws IOException { PageData pd = this.getPageData(); // 根據考試 id 獲取考試資訊 String testid = pd.getString("testid"); List<PageData> list = this.teacherFacade.selectTestById(testid); List<PageData> system = this.teacherFacade.selectSystem(); /* * 檔案大小檢測 */ long filesize = file.getSize(); long minSize = (long) system.get(0).get("file_minsize"); long maxSize = (long) system.get(0).get("file_maxsize");
// 檔案小於最小值或大於最大值; if (minSize > filesize) { session.setAttribute("min", minSize + "Byte"); return "min"; } if (maxSize < filesize) { session.setAttribute("max", maxSize + "Byte"); return "max"; } // 儲存路徑為考試名 String path = request.getSession().getServletContext() .getRealPath("/ExamSystem/" + list.get(0).getString("testname")); System.out.println("path>>" + path); String fileName = file.getOriginalFilename(); // 將檔名加入到資料庫 pd.put("submit", fileName); this.teacherFacade.updateaddfile(pd); System.out.println("fileName>>" + fileName); File dir = new File(path, fileName); System.out.println("dir.exists()>>" + dir.exists()); if (!dir.exists()) { dir.mkdirs(); } System.out.println("dir.exists()>>" + dir.exists()); // MultipartFile自帶的解析方法 file.transferTo(dir); return "ok"; }
(二)下載
2-1 前端
<form action="downTest" name="form3" id="form3" method="post"><!-- action 是請求對映的地址 --> <input type="submit" class="test_down" value="下載檢視" /> </form>
2-2 Controller
@ResponseBody @RequestMapping("/downTest") private void down(HttpServletRequest request, HttpServletResponse response) throws IOException { // 根據考試 id 獲取考試資訊 // list = this.studentFacade.selectTestById(testid); ServletContext application = request.getSession().getServletContext(); List<PageData> list = (List<PageData>) application.getAttribute("RunTest"); System.out.println(list); if (list != null) { String path = request.getServletContext().getRealPath("/") + "ExamSystem/" + list.get(0).getString("testname") + "/"; System.out.println(path); String fileName = list.get(0).getString("submit"); fileName = new String(fileName.getBytes(), "ISO8859-1");//解決無法下載中文的問題 //System.out.println(path + fileName); File file = new File(path + fileName); //System.out.println(file); if (file != null) { //System.out.println("檔案的名字:" + fileName); response.addHeader("content-disposition", "attachment;filename=" + fileName); FileUtils.copyFile(file, response.getOutputStream()); } } }
下載是會有中文名無法顯示的問題,程式碼中加入
fileName = new String(fileName.getBytes(), "ISO8859-1");
(三)打包為 zip 下載 (原文地址沒找到...)
3-1 前端
<a id="downloadInfo" href="downZip?testid=${test.get('testid')}" title="打包下載">打包下載</a>
3-2 Controller
@ResponseBody @RequestMapping("/downZip") public void downZip(HttpServletRequest request, HttpServletRequest reponse) throws IOException { PageData pd = this.getPageData(); //response.setContentType("application/x-msdownload;"); // System.out.println(pd); String testid = pd.getString("testid"); System.out.println(testid); List<PageData> list = new ArrayList<PageData>(); if (this.teacherFacade.selectTestById(testid) != null) { // 歸檔考試 pd.put("test_signal", "3"); this.teacherFacade.updateSignal(pd); list = this.teacherFacade.selectTestById(testid); } if (list != null) { try { String testName = list.get(0).getString("testname"); String sourcePath = request.getServletContext().getRealPath("/") + "ExamSystem/" + testName; System.out.println(sourcePath); String zipName = testName + ".zip"; zipName = new String(zipName.getBytes(), "ISO8859-1"); System.out.println(zipName); String zipPath = request.getServletContext().getRealPath("/") + "ExamSystem/" + zipName; File file = new File(sourcePath);// 要被壓縮的資料夾 File zipFile = new File(zipPath); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); if (file.isDirectory()) { File[] files = file.listFiles(); for (File fileSec : files) { ZipUtil.recursionZip(zipOut, fileSec, ""); } } zipOut.close(); if (zipFile != null) { System.out.println("檔案的名字:" + zipName); response.addHeader("content-disposition", "attachment;filename=" + zipName); FileUtils.copyFile(zipFile, response.getOutputStream()); } } catch (Exception e) { e.printStackTrace(); } } }
3-3 工具類
package com.ssm.util; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtil { /* * 檔案壓縮 */ public static void recursionZip(ZipOutputStream zipOut, File file, String baseDir) throws Exception { if (file.isDirectory()) { File[] files = file.listFiles(); for (File fileSec : files) { recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator); } } else { byte[] buf = new byte[1024]; InputStream input = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(baseDir + file.getName())); int len; while ((len = input.read(buf)) != -1) { zipOut.write(buf, 0, len); } input.close(); } } }
(四)刪除資料夾下的所有內容 原文地址
4-1 獲取檔案地址
String sourcePath = request.getSession().getServletContext().getRealPath("/") + "ExamSystem/" + testName;
4-2 刪除資料夾下所有內容
File sourceFile = new File(sourcePath); if (sourceFile.exists()) { DeleteFolderUtil.deleteFile(sourceFile); }
4-3 工具類
package com.ssm.util; import java.io.File; public class DeleteFolderUtil { /* * 刪除資料夾下所有內容 */ public static void deleteFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFile(files[i]); } } file.delete(); } }