檔案上傳:讀取檔案流的形式
阿新 • • 發佈:2019-02-03
傳統的上傳檔案方式是首先將檔案上傳到指定路徑,然後再從該路徑下解析檔案內容;這種方式實現比較繁瑣,並且暴漏了檔案上傳的路徑,造成了安全隱患。現在我們介紹的是另一種方式,直接讀取檔案流的方式,這種方式更加簡單安全,而且不佔用伺服器記憶體。
一. jsp頁面
1. list.jsp
<ul> <li><a class="icon" title="匯入檔案" rel="dlg_import_comment" target="dialog" width="600" height="300" href="${ctx}/admin/comment/import.jsp"><span>匯入檔案</span></a></li> <li><a class="icon" title="下載檔案模版" href="${ctx}/admin/comment/comment_template.xls"><span>下載檔案Excel模版</span></a></li> <li>line</li> </ul>
2. import.jsp
<%@ page contentType="text/html; charset=UTF-8" session="false" %> <%@ include file="/WEB-INF/jspf/import.jspf" %> <div class="pageContent"> <form method="post" action="${ctx}/admin/comment/import.do" enctype="multipart/form-data" class="pageForm" onsubmit="return iframeCallback(this, dialogAjaxDone);"> <div class="pageFormContent" layoutH="56"> <fieldset> <legend>請選擇Excel檔案,請務必按照規定的模版錄入資料</legend> <dl class="nowrap"> <dd><input class="required" type="file" name="file"/></dd> </dl> </fieldset> </div> <div class="formBar"> <ul> <li><div class="buttonActive"><div class="buttonContent"><button type="submit">匯入</button></div></div></li> <li><div class="button"><div class="buttonContent"><button class="close" type="button">關閉</button></div></div></li> </ul> </div> </form> </div>
二. controller控制層
commentController.java
注意:傳統檔案上傳方式需要在.xml檔案配置檔案上傳監聽multipartResolver,每次檔案上傳都會被監聽到並先進行一次內容解析,再將解析後的內容傳到controller層進行處理,而新方式是直接在controller層進行解析再處理,所以無需配置監聽,若配置了監聽二次解析是獲取不到檔案內容的。@RequestMapping(value = "/comment/import.do", method = RequestMethod.POST) public String doImport(HttpServletRequest req, HttpServletResponse resp) throws Exception { // 許可權驗證 if (!AuthFacade.hasRight(AUTHFUNCTIONID_ALL, true, resp)) { return null; } boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { showMessage(req, resp, 300, "沒有選擇檔案,請重新上傳", null, null); } // 計數器 int count = 0; int fail = 0; StringBuffer failBuf = new StringBuffer();// 記錄必填項為空的 StringBuffer notExistsBuf = new StringBuffer(); // 記錄不存在的 StringBuffer lengthBuf = new StringBuffer(); // 記錄超出長度的 StringBuffer ruleBuf = new StringBuffer(); // 記錄格式不正確的 Integer statusCode = 200; String msg = ""; Cell cell = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 設定上傳檔案大小的上限10m,-1表示無上限 upload.setFileSizeMax(1024 * 1024 * 10); upload.setHeaderEncoding("gbk"); // 得到所有表單欄位物件的集合 List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); showMessage(req, resp, 300, "解析上傳的檔案出錯,請稍後重試", false, false); } if (fileItems == null || fileItems.isEmpty()) { showMessage(req, resp, 300, "檔案為空,請重新上傳", false, false); } // 迭代匯入到表內資料 Iterator it = fileItems.iterator(); while (it.hasNext()) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { InputStream is = fi.getInputStream(); Workbook wb = null; try { wb = Workbook.getWorkbook(is); } catch (Exception e) { e.printStackTrace(); resp.setCharacterEncoding("UTF-8"); resp.getWriter().println(new JSONBuilder().put("statusCode", 300).put("message", "讀取Excel表格出錯,請檢查Excel表格, 或者稍後重試").toString()); return null; } // 讀取第一個工作本 Sheet sheet = wb.getSheet(0); if (sheet != null) { int rowNum = sheet.getRows(); // 聚合詞 Comment comment = null; CommentImg commentImg = null; int groupId = 0; // 團購ID int goodsId = 0; // 商品ID int userId = 0; // 馬甲ID Date createAt = null; // 評論時間 String content = ""; // 評論 String url1 = ""; // 圖片URL1 String url2 = ""; // 圖片URL2 String url3 = ""; // 圖片URL3 String url4 = ""; // 圖片URL4 String url5 = ""; // 圖片URL5 String uId = ""; String goId = ""; String grId = ""; String date = ""; long commentId = 0; // 從第二行開始拿資料 for (int i = 1; i < rowNum; i++) { List<String> str = new ArrayList<String>(); Cell[] cells = sheet.getRow(i); if (cells != null && cells.length > 0) { // A.團購ID if (0 < cells.length) { cell = cells[0]; } else { cell = null; } if (cell != null) { grId = Utils.toInput(cell.getContents()); if (Utils.isBlank(grId)) { fail++; failBuf.append((i + 1) + ";"); continue; } groupId = Utils.intValue(grId, -1); if (groupId <= 0 || null == groupService.findGroup(groupId)) { fail++; notExistsBuf.append((i + 1) + ";"); continue; } } else { fail++; failBuf.append((i + 1) + ";"); continue; } // B.商品ID if (1 < cells.length) { cell = cells[1]; } else { cell = null; } if (cell != null) { goId = Utils.toInput(cell.getContents()); if (Utils.isBlank(goId)) { fail++; failBuf.append((i + 1) + ";"); continue; } goodsId = Utils.intValue(goId, -1); if (goodsId <= 0 || null == goodsService.findGoods(goodsId)) { fail++; notExistsBuf.append((i + 1) + ";"); continue; } } else { fail++; failBuf.append((i + 1) + ";"); continue; } // C.馬甲ID if (2 < cells.length) { cell = cells[2]; } else { cell = null; } if (cell != null) { uId = Utils.toInput(cell.getContents()); if (Utils.isBlank(uId)) { fail++; failBuf.append((i + 1) + ";"); continue; } userId = Utils.intValue(uId, -1); Account account = userService.findAccount(userId); if (account == null) { fail++; notExistsBuf.append((i + 1) + ";"); continue; } } else { fail++; failBuf.append((i + 1) + ";"); continue; } // D.評論時間 if (3 < cells.length) { cell = cells[3]; } else { cell = null; } if (cell != null) { date = Utils.toInput(cell.getContents()); if (Utils.isBlank(date)) { fail++; failBuf.append((i + 1) + ";"); continue; } date = date.replace("/", "-"); boolean isDate = Utils.isValidDate(date); if (isDate == true) { createAt = Utils.parseToDate(date, "yyyy-MM-dd HH:mm:ss"); } if (createAt == null) { fail++; ruleBuf.append((i + 1) + ";"); continue; } } else { fail++; failBuf.append((i + 1) + ";"); continue; } // E.評論 if (4 < cells.length) { cell = cells[4]; } else { cell = null; } if (cell != null) { content = Utils.toInput(cell.getContents()); if (Utils.isBlank(content)) { fail++; failBuf.append((i + 1) + ";"); continue; } if (content.length() > 1000) { fail++; lengthBuf.append((i + 1) + ";"); continue; } } else { fail++; failBuf.append((i + 1) + ";"); continue; } // F.圖片URL1 if (5 < cells.length) { cell = cells[5]; } else { cell = null; } if (cell != null) { url1 = Utils.toInput(cell.getContents()); if (!Utils.isBlank(url1)) { if (url1.length() > 255) { fail++; lengthBuf.append((i + 1) + ";"); continue; } str.add(url1); } } // G.圖片URL2 if (6 < cells.length) { cell = cells[6]; } else { cell = null; } if (cell != null) { url2 = Utils.toInput(cell.getContents()); if (!Utils.isBlank(url2)) { if (url2.length() > 255) { fail++; lengthBuf.append((i + 1) + ";"); continue; } str.add(url2); } } // H.圖片URL3 if (7 < cells.length) { cell = cells[7]; } else { cell = null; } if (cell != null) { url3 = Utils.toInput(cell.getContents()); if (!Utils.isBlank(url3)) { if (url3.length() > 255) { fail++; lengthBuf.append((i + 1) + ";"); continue; } str.add(url3); } } // I.圖片URL4 if (8 < cells.length) { cell = cells[8]; } else { cell = null; } if (cell != null) { url4 = Utils.toInput(cell.getContents()); if (!Utils.isBlank(url4)) { if (url4.length() > 255) { fail++; lengthBuf.append((i + 1) + ";"); continue; } str.add(url4); } } // J.圖片URL5 if (9 < cells.length) { cell = cells[9]; } else { cell = null; } if (cell != null) { url5 = Utils.toInput(cell.getContents()); if (!Utils.isBlank(url5)) { if (url5.length() > 255) { fail++; lengthBuf.append((i + 1) + ";"); continue; } str.add(url5); } } int hasImg = 0; if (null != str && str.size() > 0) { hasImg = 1; } comment = new Comment(); comment.setGroupId(groupId); comment.setGoodsId(goodsId); comment.setUserId(userId); comment.setStatus(Comment.STATUS_NORMAL); comment.setContent(content); comment.setCreateAt(createAt); comment.setHasImg(hasImg); commentId = commentService.createComment(comment); for (String url : str) { commentImg = new CommentImg(); commentImg.setCommentId(commentId); commentImg.setImgUrl(url); commentImg.setCreateBy(userId); commentService.createCommentImg(commentImg); } count++; } } } } } resp.setCharacterEncoding("UTF-8"); msg = "成功匯入" + count + "條評論,失敗" + ((0 > fail) ? 0 : fail) + "條! "; if (fail > 0) { statusCode = 300; msg += "原因:"; if (!Utils.isBlank(failBuf.toString())) { msg += "必填項是否為空;行號為:" + failBuf.toString() + ";"; } if (!Utils.isBlank(notExistsBuf.toString())) { msg += "團購ID或商品ID或馬甲ID不存在;行號為:" + notExistsBuf.toString() + ";"; } if (!Utils.isBlank(lengthBuf.toString())) { msg += "評論內容或圖片url長度太長;行號為:" + lengthBuf.toString() + ";"; } if (!Utils.isBlank(ruleBuf.toString())) { msg += "評論時間格式不對;行號為:" + ruleBuf.toString() + ";"; } } if (fail == 0) { showMessage(req, resp, statusCode, msg, true, true); } else { showMessage(req, resp, statusCode, msg, false, false); } return null; }
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000"/>
</bean>