本组件采用Spring MVC + Jquery实现。
上传公用jsp画面:
FileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="com.cybersoft4u.framework.controller.utilities.HttpRequestHelper"%> <%@page import="java.util.*"%> <%@page import="com.cybersoft4u.framework.domain.FileUpload"%> <%@page import="java.lang.*"%> <%@page import="com.cybersoft4u.framework.domain.utilities.StringUtils"%> <%@page import="com.cybersoft4u.framework.domain.utilities.PFMConstants"%> <!-- Java class End --> <!-- force to disable jsp page cache --> <% HttpRequestHelper.disableCaching(response); %> <!-- Load or Set Default parameter Start --> <%@ include file="/common/taglibs.jsp"%> <!-- this is for EL usage --> <!-- Load or Set Default parameter End --> <html> <head> <title>基本資料</title> <!-- Import css file Start --> <!-- Import css file End --> <!-- Import javascript file Start--> <%@ include file="/common/js.jsp"%> <script type="text/javascript" src="${ctx}/js/jquery/ajaxfileupload.js"></script> <!-- Import javascript file End--> <!-- JavaScript for this page only Start --> <script type="text/javascript" language="JavaScript"> //校驗上傳檔案表單 function doCkeck(){ var agt = navigator.userAgent.toLowerCase();//判斷os var strFile = document.getElementById("fileData").value; if(strFile =="" || strFile == null){ alert("請選擇上傳檔案!"); return false; }else{ //檔案擴展名稱 var fileExt = document.getElementById("fileData").value.substr(document.getElementById("fileData").value.lastIndexOf(".")).toLowerCase(); var allowExt = ".jpg|.gif|.png|.bmp|.pdf|.doc|.docx|.xls|.xlsx|.msg|.xml|.txt|.mail|.ppt|.zip|"; if(allowExt != 0 && allowExt.indexOf(fileExt + "|") == -1){ alert("請上傳【.jpg|.gif|.png|.bmp|.pdf|.doc|.docx|.xls|.xlsx|.msg|.xml|.txt|.mail|.ppt|.zip】類型的檔案!"); return false; } } return true; } //ajax上載文件,動態刷新文件列表 function ajaxFileUpload() { /* prepareing ajax file upload url: the url of script file handling the uploaded files fileElementId: the file type of input element id and it will be the index of $_FILES Array() dataType: it support json, xml secureuri:use secure protocol success: call back function when the ajax complete error: callback function when the ajax failed */ if(doCkeck()){//先判斷是否有選擇檔案 var comments = $("#comments").val();//將comments傳遞過去 //先校驗檔案大小是否符合限制規定 $.ajaxFileUpload ( { url:'<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/uploadFile.htm', secureuri:false, fileElementId:'fileData', dataType: 'json', data:{ "comments":comments }, success: function (data, status) { //清空input框內容 $("#fileData").attr("value", ""); $("#comments").attr("value", ""); var html = ""; //從map中取回調的資料 var errors = data['fileNameRepeat'];//檔案名稱重復錯誤信息 var fileLists = data['fileLists'];//檔案上載列表 var fileSizeSmall = data['fileSizeSmall'];//檔案大小不能為0 if(fileSizeSmall != null){ alert("檔案大小不能為0!"); $.each(fileLists,function(index,comm){ html+="<tr class='table-odd-row'>" +"<td class='table-other-column'><a href='javascript:void(0)' οnclick='return deleteFile("+fileLists[index].fileNo+");'><img src='${ctx}/images/u78.png' width='16' height='16' border='0' alt='刪除'></a></td>" +"<td class='table-string-column'><a href='<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/downloadFile.htm?wh=temp&fileName="+fileLists[index].aliasFileName+"&srcFileName="+fileLists[index].fileName+"' οnclick='return checkFileExist(\""+fileLists[index].aliasFileName+"\");'>"+fileLists[index].fileName+"</a></td>" +"<td class='table-string-column'>"+fileLists[index].strUploadDate+"</td>" +"<td class='table-string-column'>"+fileLists[index].uploadUser+"</td>" +"<td class='table-num-column'>"+fileLists[index].fileSize+"</td>" +"<td class='table-string-column'>"+fileLists[index].comments+"</td>" +"</tr>"; }); }else if(errors != null){ alert("檔案名稱重復!"); $.each(fileLists,function(index,comm){ html+="<tr class='table-odd-row'>" +"<td class='table-other-column'><a href='javascript:void(0)' οnclick='return deleteFile("+fileLists[index].fileNo+");'><img src='${ctx}/images/u78.png' width='16' height='16' border='0' alt='刪除'></a></td>" +"<td class='table-string-column'><a href='<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/downloadFile.htm?wh=temp&fileName="+fileLists[index].aliasFileName+"&srcFileName="+fileLists[index].fileName+"' οnclick='return checkFileExist(\""+fileLists[index].aliasFileName+"\");'>"+fileLists[index].fileName+"</a></td>" +"<td class='table-string-column'>"+fileLists[index].strUploadDate+"</td>" +"<td class='table-string-column'>"+fileLists[index].uploadUser+"</td>" +"<td class='table-num-column'>"+fileLists[index].fileSize+"</td>" +"<td class='table-string-column'>"+fileLists[index].comments+"</td>" +"</tr>"; }); }else{ $.each(fileLists,function(index,comm){ html+="<tr class='table-odd-row'>" +"<td class='table-other-column'><a href='javascript:void(0)' οnclick='return deleteFile("+fileLists[index].fileNo+");'><img src='${ctx}/images/u78.png' width='16' height='16' border='0' alt='刪除'></a></td>" +"<td class='table-string-column'><a href='<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/downloadFile.htm?wh=temp&fileName="+fileLists[index].aliasFileName+"&srcFileName="+fileLists[index].fileName+"' οnclick='return checkFileExist(\""+fileLists[index].aliasFileName+"\");'>"+fileLists[index].fileName+"</a></td>" +"<td class='table-string-column'>"+fileLists[index].strUploadDate+"</td>" +"<td class='table-string-column'>"+fileLists[index].uploadUser+"</td>" +"<td class='table-num-column'>"+fileLists[index].fileSize+"</td>" +"<td class='table-string-column'>"+fileLists[index].comments+"</td>" +"</tr>"; }); } $("#tab1 tbody").html(html); }, error: function (data, status, e) { alert(e); } } ) } //防止刷新 return false; } //ajax動態刪除档案 function deleteFile(fileNo){ if(confirm('确定刪除?')){ //ajax刪除文件 $.get("<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/deleteFile.htm",//URL {fileNo:fileNo},//傳入的參數 function(data, textStatus){//回調方法 var fileLists = JSON.parse(data); //先移除之前的信息,再加载 $("#tab1 tbody").find('tr:not(:first)').remove(); var html = ""; $.each(fileLists,function(index,comm){ html+="<tr class='table-odd-row'>" +"<td class='table-other-column'><a href='javascript:void(0)' οnclick='return deleteFile("+fileLists[index].fileNo+");'><img src='${ctx}/images/u78.png' width='16' height='16' border='0' alt='刪除'></a></td>" +"<td class='table-string-column'><a href='<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/downloadFile.htm?wh=temp&fileName="+fileLists[index].aliasFileName+"&srcFileName="+fileLists[index].fileName+"' οnclick='return checkFileExist(\""+fileLists[index].aliasFileName+"\");'>"+fileLists[index].fileName+"</a></td>" +"<td class='table-string-column'>"+fileLists[index].strUploadDate+"</td>" +"<td class='table-string-column'>"+fileLists[index].uploadUser+"</td>" +"<td class='table-num-column'>"+fileLists[index].fileSize+"</td>" +"<td class='table-string-column'>"+fileLists[index].comments+"</td>" +"</tr>"; }); $("#tab1 tbody").html(html); }); return false; } } //ajax初始化上載列表,供修改使用 function initFileUpload() { //ajax刪除文件 $.get("<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/initUploadFile.htm",//URL {},//傳入的參數 function(data, textStatus){//回調方法 var fileLists = JSON.parse(data); //先移除之前的信息,再加载 $("#tab1 tbody").find('tr:not(:first)').remove(); var html = ""; $.each(fileLists,function(index,comm){ html+="<tr class='table-odd-row'>" +"<td class='table-other-column'><a href='javascript:void(0)' οnclick='return deleteFile("+fileLists[index].fileNo+");'><img src='${ctx}/images/u78.png' width='16' height='16' border='0' alt='刪除'></a></td>" +"<td class='table-string-column'><a href='<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/downloadFile.htm?wh=real&fileName="+fileLists[index].aliasFileName+"&srcFileName="+fileLists[index].fileName+"' οnclick='return checkFileExist(\""+fileLists[index].aliasFileName+"\");'>"+fileLists[index].fileName+"</a></td>" +"<td class='table-string-column'>"+fileLists[index].strUploadDate+"</td>" +"<td class='table-string-column'>"+fileLists[index].uploadUser+"</td>" +"<td class='table-num-column'>"+fileLists[index].fileSize+"</td>" +"<td class='table-string-column'>"+fileLists[index].comments+"</td>" +"</tr>"; }); $("#tab1 tbody").html(html); }); return false; } //判斷檔案是否存在 function checkFileExist(fileName){ var flag = null; $.ajax({url:"<%=request.getContextPath()%>/<%=PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO%>/checkFileName.htm", //URL cache:"False", type:"get", async: false,//同步校驗 data:{fileName:fileName},//傳入的參數 success:function(data, textStatus){//回調方法 var isOk = JSON.parse(data); if(isOk != null){ if(isOk == false){ alert("檔案不存在!"); flag = false; }else if(isOk == true){ flag = true; } } }}); return flag; } </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body class="bodystyle"> <!-- Include default information page and tab page Start--> <!-- Include default information page and tab page End--> <!-- This page Start --> <form:form id="uploadForm" name="uploadForm" action="#" method="post" enctype="multipart/form-data" οnsubmit="return false;"> <!-- *** Hidden Fields Area *** --> <!-- *** End of Hidden Fields --> <%-- <fmt:setLocale value="" /> <fmt:setBundle var="" basename="" /> --%> <!--Your Content Form--> <div> <hr /> <%=request.getAttribute("uploadMsg") == null?"":request.getAttribute("uploadMsg")%> <br/> </div> <c:if test="${updateDisabled || createDisabled || detailDisabled}"> <table class="tablestyle" cellspacing="0" cellpadding="0"> <tr> <td> <table class="tablestyle1" cellspacing="2" cellpadding="1"> <tr class="tdstyle1"> <td class="tdstyle1" >上載檔案:</td> <td class="tdstyle2"><input type="file" class="textbox_char_450" name="fileData" id="fileData" value="瀏覽" /></td> <td class="tdstyle1">備註:</td> <td class="tdstyle2"> <input id="comments" class="textbox_char_150" name="comments" maxlength="650"/> <input id="mainTable" type=button class="button_2" value="上載" οnclick="return ajaxFileUpload();" /> </td> </tr> </table> </td> </tr> </table> </c:if> <!-- 表1 --> <table class="tablestyle" cellspacing="0" cellpadding="0"> <tr> <td> <table class="tablestyle1" id="tab1" cellpadding="2" cellspacing="1"> <thead> <tr> <th class="headers" scope="col">處理</th> <th class="headers" scope="col">檔案名稱</th> <th class="headers" scope="col">上載時間</th> <th class="headers" scope="col">上載人</th> <th class="headers" scope="col">檔案大小</th> <th class="headers" scope="col">附注</th> </tr> </thead> <tbody> </tbody> </table> </td> </tr> </table> <!-- 表1結束 --> </form:form> <!-- This page End --> </body> </html>
Controller
FileUploadController.javapackage com.cybersoft4u.framework.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.cybersoft4u.framework.domain.FileUpload; import com.cybersoft4u.framework.domain.ValueObject; import com.cybersoft4u.framework.domain.utilities.FrameworkConstants; import com.cybersoft4u.framework.domain.utilities.PFMConstants; import com.cybersoft4u.framework.domain.utilities.PMSConstants; import com.cybersoft4u.framework.dto.upm.UserRightsDTO; import com.cybersoft4u.framework.persistence.exception.FrameworkCommonException; import com.cybersoft4u.framework.service.common.Context; import com.cybersoft4u.framework.service.common.FrameworkRequest; import com.cybersoft4u.framework.service.common.Request; /** * Purpose: 檔案上載下載元件controller。 * @author: shihuangzhe.com * @since: JDK 1.6 * @date: 2012/1/13 * @MaintenancePersonnel: shihuangzhe.com */ @Controller @RequestMapping(PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO) public class FileUploadController extends FrameworkMultiActionController{ private static final Log logger = LogFactory.getLog(FileUploadController.class); ServletConfig config; /** * Constructor--. */ public FileUploadController(){ } /** * Purpose: 上載檔案--不寫入db. * @author: liongao * @param fileUpload * @param request * @param response * @throws Exception * @return: Map<Integer,FileUpload> */ @SuppressWarnings("unchecked") @RequestMapping(FrameworkConstants.OPERATION_UPLOAD_FILE) public @ResponseBody Map createFile(FileUpload fileUpload ,HttpServletResponse response) throws Exception{ logger.info("Enter FileUploadController.createFile(),fileUpload="+fileUpload); try { //HttpServletRequest HttpServletRequest request = super.getHttpRequest(); //判斷檔案大小 if(fileUpload.getFileData().getSize() <= 0){ //從session中取得上載列表 Map<Integer,FileUpload> testResult = request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST)==null?new LinkedHashMap<Integer,FileUpload>():(Map<Integer,FileUpload>)request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST); //存儲錯誤信息和上載檔案列表 Map<String,Object> map = new HashMap<String,Object>(); map.put(FrameworkConstants.PAGE_FILE_LIST, testResult); map.put(FrameworkConstants.FILE_SIZE_SMALL, FrameworkConstants.FILE_SIZE_SMALL); request.getSession().setAttribute(FrameworkConstants.FILE_MAP, map); request.getSession().setAttribute(FrameworkConstants.PAGE_FILE_LIST, testResult); return map; } //存儲錯誤信息和上載檔案列表 Map<String,Object> map = new HashMap<String,Object>(); //服務器根 String rootPath = request.getSession().getServletContext().getRealPath(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK); //return list Map<Integer,FileUpload> result = new LinkedHashMap<Integer,FileUpload>(); //從session中取得上載列表 Map<Integer,FileUpload> testResult = request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST)==null?new LinkedHashMap<Integer,FileUpload>():(Map<Integer,FileUpload>)request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST); //校驗檔案名稱 // 檔案流對象 MultipartFile file = fileUpload.getFileData(); String fileName = file.getOriginalFilename(); if(testResult != null && testResult.size() > 0){//有,則校驗檔案名 for(Map.Entry<Integer, FileUpload> oneFile:testResult.entrySet()){ if(fileName.equals(oneFile.getValue().getFileName())){ map.put(FrameworkConstants.FILE_NAME_REPEAT, FrameworkConstants.FILE_NAME_REPEAT); map.put(FrameworkConstants.PAGE_FILE_LIST, testResult); request.getSession().setAttribute(FrameworkConstants.PAGE_FILE_LIST, testResult); return map; } } //如果檔案名校驗通過 //處理請求--参数為false表示不分頁 Request req = new FrameworkRequest(); //將FileUpload存入context中 req.setValueToContext(PFMConstants.PFM_PAGE_COMMAND_NAME_FILEUPLOAD_INFO, fileUpload); //將testResult存入context中 req.setValueToContext(FrameworkConstants.PAGE_TEMP_FILE_LIST, testResult); //獲取當前登陸系統者 UserRightsDTO user = getUser(); //將當前登陸者信息存入context req.setValueToContext(PFMConstants.PFM_USER_DTO, user); //將rootPath存儲與context中 req.setValueToContext(FrameworkConstants.FILE_UPLOAD_ROOT_PATH, rootPath); //將臨時上載路徑存儲與context中 req.setValueToContext(FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH, FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH); //設定模組 req.setModule(PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO); //設定操作 req.setOperation(FrameworkConstants.OPERATION_UPLOAD_FILE); //執行請求 req = super.process(req); //獲取返回結果 result = (Map<Integer,FileUpload>)req.getContext().getValue(FrameworkConstants.PAGE_TEMP_FILE_LIST); map.put(FrameworkConstants.PAGE_FILE_LIST, result); request.getSession().setAttribute(FrameworkConstants.FILE_MAP, map); request.getSession().setAttribute(FrameworkConstants.PAGE_FILE_LIST, testResult); return map; }else{ //處理請求--参数為false表示不分頁 Request req = new FrameworkRequest(); //將FileUpload存入context中 req.setValueToContext(PFMConstants.PFM_PAGE_COMMAND_NAME_FILEUPLOAD_INFO, fileUpload); //將testResult存入context中 req.setValueToContext(FrameworkConstants.PAGE_TEMP_FILE_LIST, testResult); //獲取當前登陸系統者 UserRightsDTO user = getUser(); //將當前登陸者信息存入context req.setValueToContext(PFMConstants.PFM_USER_DTO, user); //將rootPath存儲與context中 req.setValueToContext(FrameworkConstants.FILE_UPLOAD_ROOT_PATH, rootPath); //將臨時上載路徑存儲與context中 req.setValueToContext(FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH, FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH); //設定模組 req.setModule(PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO); //設定操作 req.setOperation(FrameworkConstants.OPERATION_UPLOAD_FILE); //執行請求 req = super.process(req); //獲取返回結果 result = (Map<Integer,FileUpload>)req.getContext().getValue(FrameworkConstants.PAGE_TEMP_FILE_LIST); map.put(FrameworkConstants.PAGE_FILE_LIST, result); request.getSession().setAttribute(FrameworkConstants.FILE_MAP, map); request.getSession().setAttribute(FrameworkConstants.PAGE_FILE_LIST, result); return map; } } catch (Exception e) { logger.error("Enter FileUploadController.createFile()," + e.getMessage(), e); } return null; } /** * Purpose: 刪除檔案. * @author: liongao * @param fileNo * @param fileName * @param request * @param response * @throws Exception * @return: String */ @SuppressWarnings("unchecked") @RequestMapping(FrameworkConstants.OPERATION_DELETE_FILE) public @ResponseBody Map<Integer,FileUpload> deleteFile(@RequestParam(FrameworkConstants.FILE_NO)String fileNo, HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.info("Enter FileUploadController.deleteFile()"); //獲取session的list Map<Integer,FileUpload> result = (Map<Integer,FileUpload>)request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST); try{ //處理請求--参数為false表示不分頁 Request req = new FrameworkRequest(); //將fileNo存入context中 req.setValueToContext(FrameworkConstants.FILE_NO, fileNo); //將result存入context中 req.setValueToContext(FrameworkConstants.PAGE_UPLOAD_FILE_LIST, result); //設定模組 req.setModule(PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO); //設定操作 req.setOperation(PFMConstants.OPERATION_DELETE_FILE); //執行請求 req = super.process(req); //獲取返回結果 result = (Map<Integer,FileUpload>)req.getContext().getValue(FrameworkConstants.PAGE_UPLOAD_FILE_LIST); request.getSession().setAttribute(FrameworkConstants.PAGE_FILE_LIST, result); return result; } catch (Exception e) { logger.error("FileUploadController.deleteFile()--> " + e, e); } return result; } /** * Purpose:ajax初始化上載列表,為修改畫面帶入資料庫數據 * @author: liongao * @param request * @param response * @throws Exception * @return: Map<Integer,FileUpload> */ @SuppressWarnings("unchecked") @RequestMapping(FrameworkConstants.OPERATION_INIT_UPLOAD_FILE) public @ResponseBody Map<Integer,FileUpload> initUploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{ //1.從session 取得檔案 Map<Integer,FileUpload> result = null; try { result = request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST)==null?new LinkedHashMap<Integer,FileUpload>():(Map<Integer,FileUpload>)request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST); } catch (Exception e) { logger.error("FileUploadController.deleteFile()--> " + e, e); } return result; } /** * Purpose: 下載檔案 * @author: liongao * @param wh * @param fileName * @param srcFileName * @param request * @param response * @throws Exception * @return: void */ @RequestMapping(FrameworkConstants.OPERATION_DOWNLOAD_FILE) public void downloadFile(String wh,String fileName, String srcFileName, HttpServletRequest request,HttpServletResponse response) throws Exception{ logger.info("Enter FileUploadController.downloadFile()"); fileName = new String(fileName.getBytes(FrameworkConstants.ISO_LANG),FrameworkConstants.UTF_LANG); srcFileName = new String(srcFileName.getBytes(FrameworkConstants.ISO_LANG),FrameworkConstants.UTF_LANG); logger.debug("downloadFile.fileName --->> " + fileName); logger.debug("downloadFile.srcFileName --->> " + srcFileName); //檔案原始下載名稱 srcFileName = srcFileName.substring(srcFileName.indexOf(FrameworkConstants.PAGE_PARAM_UNDER_LINE_MARK) + 1).substring(srcFileName.substring(srcFileName.indexOf(FrameworkConstants.PAGE_PARAM_UNDER_LINE_MARK) + 1).indexOf(FrameworkConstants.PAGE_PARAM_UNDER_LINE_MARK) + 1); response.reset(); response.setHeader(FrameworkConstants.CONTENT_DISPOSITION, FrameworkConstants.ATTACHMENT + FrameworkConstants.SEMI_COLON + FrameworkConstants.FILE_NAME + FrameworkConstants.EQUAL_SIGN + URLEncoder.encode(srcFileName,FrameworkConstants.UTF_LANG).replace("+","%20")); //服務器根路徑 String rootPath = request.getSession().getServletContext().getRealPath(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; String location = FrameworkConstants.NULL_STRING; //檔案類型 String fileExt = fileName.substring( fileName.indexOf(".") + 1); fileName = fileName.trim();//拿掉空格 //區分下載臨時檔案,還是真實檔案 wh=temp為臨時,wh=real為真實 if(FrameworkConstants.TRUE.equals(checkSystemOS())){//windows if(FrameworkConstants.TEMP_DOWN.equals(wh)){ location = rootPath + FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK + fileName; }else if(FrameworkConstants.REAL_DOWN.equals(wh)){ location = rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)).substring(0,rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)).lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)) + FrameworkConstants.PAGE_PARAM_SLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK + fileName; } }else if(FrameworkConstants.FALSE.equals(checkSystemOS())){//Linux if(FrameworkConstants.TEMP_DOWN.equals(wh)){ location = rootPath + FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + fileName; }else if(FrameworkConstants.REAL_DOWN.equals(wh)){ location = rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)).substring(0,rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)).lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)) + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + fileName; } } //set ContentType if (fileExt != null && fileExt.equalsIgnoreCase(FrameworkConstants.PDF)) { response.setContentType(FrameworkConstants.MS_DOWNLOAD); } else if (fileExt != null && fileExt.equalsIgnoreCase(FrameworkConstants.DOC)) { response.setContentType(FrameworkConstants.MS_DOWNLOAD); }else if (fileExt != null && fileExt.equalsIgnoreCase(FrameworkConstants.XLS)) { response.setContentType(FrameworkConstants.MS_DOWNLOAD); } try { //讀取檔案流 bis = new BufferedInputStream(new FileInputStream(location)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[8192]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } }catch (FileNotFoundException e) { logger.error("Enter FileUploadController.downloadFile()"+e,e); } catch (IOException e) { logger.error("Enter FileUploadController.downloadFile()"+e,e); }finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } /** * Purpose:ajax校驗檔案是否存在 * @author: liongao * @param fileName * @param request * @param response * @throws Exception * @return: boolean */ @RequestMapping(FrameworkConstants.OPERATION_CHECK_UPLOAD_FILE_NAME) public @ResponseBody boolean checkFileExist(String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.info("Enter FileUploadController.checkFileExist()"); //服務器根 String rootPath = request.getSession().getServletContext().getRealPath(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK); fileName = new String(fileName.getBytes(FrameworkConstants.ISO_LANG),FrameworkConstants.UTF_LANG); boolean flag = true; try { String tempPath = FrameworkConstants.NULL_STRING; String realPath = FrameworkConstants.NULL_STRING; //區分os if(FrameworkConstants.TRUE.equals(checkSystemOS())){//windows tempPath = rootPath + FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK + fileName; realPath = rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)).substring(0,rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)).lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)) + FrameworkConstants.PAGE_PARAM_SLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK + fileName; }else if(FrameworkConstants.FALSE.equals(checkSystemOS())){//Linux tempPath = rootPath + FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + fileName; realPath = rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)).substring(0,rootPath.substring(0,rootPath.lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)).lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)) + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + fileName; } File tempFile = new File(tempPath); File realFile = new File(realPath); logger.debug("checkFileExist.tempFile --->> " + tempFile); logger.debug("checkFileExist.realFile --->> " + realFile); if(!tempFile.exists() && !realFile.exists()){ flag = false; } } catch (Exception e) { logger.error("FileUploadController.deleteFile()--> " + e, e); } return flag; } /** * Purpose: 判斷os是linux還是windows * @author: liongao * @return: String */ private String checkSystemOS(){ String returnStr = FrameworkConstants.NULL_STRING; //判斷os是windows還是linux Properties prop = System.getProperties(); String os = prop.getProperty(FrameworkConstants.OS_NAME); String sysWin = FrameworkConstants.WINDOWS_SYSTEM; String sysLinux = FrameworkConstants.LINUX_SYSTEM; if(os.toLowerCase().indexOf(sysWin) != -1){//windows returnStr = FrameworkConstants.TRUE; }else if(os.toLowerCase().equals(sysLinux)){//Linux returnStr = FrameworkConstants.FALSE; } return returnStr; } @Override public void customPostInit(HttpServletRequest request, Context ctx) throws Exception { // TODO Auto-generated method stub } @Override public boolean validate(ValueObject<?> parmemters) throws FrameworkCommonException { // TODO Auto-generated method stub return false; } /** * 更新fileUploadDB中的資料 * Purpose: * @author: stellerwang * @param formNum * @return * @return: String */ @RequestMapping(value=PMSConstants.OPERATION_LOAD_UPDATEDB) public String loadUpdateDB(String projectNo,String source,String extraId,HttpServletRequest request,HttpServletResponse response){ try{ //從session中取得上載列表 Map<Integer,FileUpload> result = request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST)==null?new LinkedHashMap<Integer,FileUpload>():(Map<Integer,FileUpload>)request.getSession().getAttribute(FrameworkConstants.PAGE_FILE_LIST); //處理請求 Request req = new FrameworkRequest(); //將上載列表存入context中 req.setValueToContext(FrameworkConstants.PAGE_TEMP_FILE_LIST, result); req.setModule(PFMConstants.PFM_MODULE_FILE_UPLOAD_INFO); req.setOperation(PMSConstants.OPERATION_LOAD_UPDATEDB); req.setValueToContext(FrameworkConstants.PROJECT_NO,projectNo); req.setValueToContext(FrameworkConstants.HANDLE_SOURCE, source); req.setValueToContext(FrameworkConstants.EXTRA_ID, extraId); req = super.process(req); }catch(Exception e){ logger.error("FileUploadController.loadUpdateDB()-->" + e, e); } return null; } }
Service
FileUploadInfoServiceImpl.java
package com.cybersoft4u.framework.service.pfm; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import com.cybersoft4u.framework.domain.FileUpload; import com.cybersoft4u.framework.domain.utilities.FrameworkConstants; import com.cybersoft4u.framework.domain.utilities.PFMConstants; import com.cybersoft4u.framework.dto.upm.UserRightsDTO; import com.cybersoft4u.framework.persistence.common.FrameworkMessage; import com.cybersoft4u.framework.persistence.common.FrameworkMessageCode; import com.cybersoft4u.framework.persistence.common.PfmMessageCode; import com.cybersoft4u.framework.persistence.common.PmsMessageCode; import com.cybersoft4u.framework.persistence.exception.FrameworkServiceException; import com.cybersoft4u.framework.persistence.pfm.FileUploadInfoDAO; import com.cybersoft4u.framework.service.common.AtomicService; import com.cybersoft4u.framework.service.common.Request; import com.cybersoft4u.framework.service.exception.FacadeException; /** * Purpose: 上傳文檔記錄表Service Impl * @author: shihuangzhe.com * @since: JDK 1.6 * @date: 2011-12-30 * @MaintenancePersonnel: shihuangzhe.com */ @Service(value="fileUploadInfoService") @Transactional(propagation=Propagation.REQUIRED) public class FileUploadInfoServiceImpl extends AtomicService implements FileUploadInfoService { //logger private static final Log logger = LogFactory.getLog(FileUploadInfoServiceImpl.class); //文檔上傳資料DAO @Autowired(required=true) private FileUploadInfoDAO fileUploadInfoDAO = null; /** * @param fileUploadInfoDAO the fileUploadInfoDAO to set */ public void setFileUploadInfoDAO(FileUploadInfoDAO fileUploadInfoDAO) { this.fileUploadInfoDAO = fileUploadInfoDAO; } /** * Constructor--. */ public FileUploadInfoServiceImpl() { super(); } /** (non-Javadoc) * @see com.cybersoft4u.framework.service.common.Module#process(com.cybersoft4u.framework.service.common.Request) */ @Override public void process(Request req) throws FacadeException { //獲取請求operation String operation = req.getOperation(); try{ //上載檔案---假上載 if(PFMConstants.OPERATION_UPLOAD_FILE.equals(operation)){ createFile(req); } //刪除檔案 else if(PFMConstants.OPERATION_DELETE_FILE.equals(operation)){ deleteFile(req); } //更新fileUploadDB中的資料 else if(PFMConstants.OPERATION_LOAD_UPDATEDB.equals(operation)){ String projectNo = (String) req.getContext().getValue(FrameworkConstants.PROJECT_NO); String source = (String) req.getContext().getValue(FrameworkConstants.HANDLE_SOURCE); String extraId = (String) req.getContext().getValue(FrameworkConstants.EXTRA_ID); //上傳檔案 //從req中取出上載列表 Map<Integer,FileUpload> tempResult = (Map<Integer,FileUpload>)req.getContext().getValue(FrameworkConstants.PAGE_TEMP_FILE_LIST); this.fileUploadInfoDAO.updateUploadFileInfo(tempResult, projectNo, source, extraId, PmsMessageCode.FILE_MANAGEMENT); } }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoServiceImpl.process()-->" + e, e); FrameworkMessage message = new FrameworkMessage(FrameworkMessage.STATUS_FAILURE, e.getErrorCode(), (String[])e.getArguments()); throw new FrameworkServiceException(message); }catch (Exception e){ logger.error("Error Exception FileUploadInfoServiceImpl.process()-->" + e, e); throw new FrameworkServiceException(FrameworkMessageCode.UNKNOWN_SYSTEM_ERROR); } } /** * Purpose: 上載檔案--不寫入db. * @author: liongao * @param req * @throws FrameworkServiceException * @return: Map<Integer,FileUpload> */ @SuppressWarnings("unchecked") private Map<Integer,FileUpload> createFile(Request req) throws FrameworkServiceException{ logger.info("Enter FileUploadInfoServiceImpl.createFile()"); try{ //得到請求的消息fileUpload FileUpload fileUpload = (FileUpload) req.getContext().getValue(PFMConstants.PFM_PAGE_COMMAND_NAME_FILEUPLOAD_INFO); if(fileUpload == null) { logger.error("Error FileUploadInfoServiceImpl.createFile(),Context value fileUpload is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } //return list Map<Integer,FileUpload> result = new LinkedHashMap<Integer,FileUpload>(); // 檔案流對象 MultipartFile file = fileUpload.getFileData(); //得到請求的消息testResult Map<Integer,FileUpload> testResult = (Map<Integer,FileUpload>) req.getContext().getValue(FrameworkConstants.PAGE_TEMP_FILE_LIST); if(!CollectionUtils.isEmpty(testResult)){ result = testResult; } //得到請求的消息uploadUser--上載人 String uploadUser = FrameworkConstants.NULL_STRING; UserRightsDTO user = (UserRightsDTO) req.getContext().getValue(PFMConstants.PFM_USER_DTO); if(user == null){ logger.error("Error FileUploadInfoServiceImpl.createFile(),Context value user is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } uploadUser = user.getEmpNm(); //得到請求的消息rootPath--服務器根路徑 String rootPath = (String) req.getContext().getValue(FrameworkConstants.FILE_UPLOAD_ROOT_PATH); //得到請求的消息TEMP_UPLOAD_FOLDER_PATH--服務器上載臨時路徑 String TEMP_UPLOAD_FOLDER_PATH = (String) req.getContext().getValue(FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH); //上載檔案 //檔案名稱 --保留空格 String fileName = file.getOriginalFilename(); //檔案別名(時間戳_模組_檔案名) ---去掉空格 String aliasFileName = System.currentTimeMillis() + FrameworkConstants.PAGE_PARAM_UNDER_LINE_MARK + req.getModule() + FrameworkConstants.PAGE_PARAM_UNDER_LINE_MARK + fileName.replace(" ", "").trim(); //上載時間 Date uploadTime = new Date(); //格式化日期 SimpleDateFormat sf =new SimpleDateFormat(FrameworkConstants.DT_FMT_YYYYMMDD_SLASH); //上載人 //uploadUser //檔案大小 long fileSize = file.getSize()/1024; //附注 String comments = fileUpload.getComments(); //檔案路徑---存放位置 String filePath = FrameworkConstants.NULL_STRING; if(FrameworkConstants.TRUE.equals(this.fileUploadInfoDAO.checkSystemOS())){//windows filePath = rootPath + TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK; }else if(FrameworkConstants.FALSE.equals(this.fileUploadInfoDAO.checkSystemOS())){//Linux filePath = rootPath + TEMP_UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK; } logger.info("filePath -->> "+filePath); File fileDir = new File(filePath); //目錄不存在,則創建目錄 if(!fileDir.exists()){ fileDir.mkdirs(); } //檔案類型 String fileType = fileName.substring(fileName.indexOf(PFMConstants.DOT) + 1); //項目編號 String projectNo = fileUpload.getProjectNo(); InputStream inputStream = null; OutputStream outputStream = null; if(file.getSize() > 0){ inputStream = file.getInputStream(); outputStream = new FileOutputStream(filePath+aliasFileName); int readBytes = 0; byte[] buffer = new byte[8192]; while((readBytes = inputStream.read(buffer, 0, 8192)) != -1){ outputStream.write(buffer, 0, readBytes); } outputStream.close(); inputStream.close(); //2.存入session中 FileUpload fileUploadInfo = new FileUpload(); fileUploadInfo.setFileName(fileName); fileUploadInfo.setAliasFileName(aliasFileName); fileUploadInfo.setUploadUser(uploadUser); fileUploadInfo.setStrUploadDate(sf.format(uploadTime)); fileUploadInfo.setUploadDate(uploadTime); fileUploadInfo.setFileSize(fileSize+FrameworkConstants.FILE_SIZE_K); fileUploadInfo.setComments(comments); fileUploadInfo.setLoaciton(filePath+aliasFileName); fileUploadInfo.setFileType(fileType); fileUploadInfo.setProjectNo(projectNo); //設置檔案是否真正上傳(檔案不寫入db,則標記為false) fileUploadInfo.setFlag(false); if(CollectionUtils.isEmpty(result)){ //set fileNO fileUploadInfo.setFileNo(result.size()); //在list中標記檔案 result.put(result.size(),fileUploadInfo); }else if(result != null && result.size() > 0){ int i = 1; //循環result,保証key不能重復,否則會被覆蓋 for(Map.Entry<Integer,FileUpload> oneFile:result.entrySet()){ i += oneFile.getKey(); } //set fileNO fileUploadInfo.setFileNo(i); //在list中標記檔案 result.put(i,fileUploadInfo); } } //將返回結果存儲與context中 req.getContext().putValue(FrameworkConstants.PAGE_TEMP_FILE_LIST, result); return result; }catch (FrameworkServiceException e) { logger.error("Exception FileUploadInfoServiceImpl.createFile()-->"); throw new FrameworkServiceException(PfmMessageCode.FILE_UPLOAD_FAILURE, new String[]{FrameworkConstants.PARAM_BLANK,FrameworkConstants.PARAM_BLANK}); } catch (Exception e) { logger.error("Exception FileUploadInfoServiceImpl.createFile()-->"); throw new FrameworkServiceException(PfmMessageCode.FILE_UPLOAD_FAILURE, new String[]{FrameworkConstants.PARAM_BLANK,FrameworkConstants.PARAM_BLANK}); } } /** * Purpose: 刪除檔案 * @author: liongao * @param req * @throws FrameworkServiceException * @return: Map<String,FileUpload> */ @SuppressWarnings("unchecked") private Map<Integer,FileUpload> deleteFile(Request req) throws FrameworkServiceException{ logger.info("Enter FileUploadInfoServiceImpl.deleteFile()"); try{ //得到請求的消息fileNo String fileNo = (String) req.getContext().getValue(FrameworkConstants.FILE_NO); if(fileNo == null) { logger.error("Error FileUploadInfoServiceImpl.createFile(),Context value fileNo is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } //得到請求消息result Map<Integer,FileUpload> result = (Map<Integer,FileUpload>)req.getContext().getValue(FrameworkConstants.PAGE_UPLOAD_FILE_LIST); //循環,從list中找到該筆檔案 for(Map.Entry<Integer, FileUpload> oneFile:result.entrySet()){ if(StringUtils.hasText(fileNo) && Integer.parseInt(fileNo) == oneFile.getKey()){ //1.從session中刪除 result.remove(oneFile.getKey()); //2.從服務器中刪除檔案 //獲取檔案路徑 String path = oneFile.getValue().getLoaciton(); if(StringUtils.hasText(path)){ File file = new File(path); // 檔案存在 if(file.exists()){ //真實路徑的檔案,則不刪除 if(FrameworkConstants.TRUE.equals(this.fileUploadInfoDAO.checkSystemOS())){//windows if(path.indexOf( FrameworkConstants.PAGE_PARAM_SLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH) == -1){ //刪除檔案 file.delete(); } }else if(FrameworkConstants.FALSE.equals(this.fileUploadInfoDAO.checkSystemOS())){//Linux if(path.indexOf( FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH) == -1){ //刪除檔案 file.delete(); } } } } return result; } } //將結果存入context req.getContext().putValue(FrameworkConstants.PAGE_UPLOAD_FILE_LIST,result); return result; }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoServiceImpl.deleteFile()-->"); throw new FrameworkServiceException(PfmMessageCode.FILE_NOT_FOUND_EXCEPTION, new String[]{FrameworkConstants.PARAM_BLANK,FrameworkConstants.PARAM_BLANK}); } catch (Exception e) { logger.error("Exception FileUploadInfoServiceImpl.deleteFile()-->"); throw new FrameworkServiceException(PfmMessageCode.FILE_NOT_FOUND_EXCEPTION, new String[]{FrameworkConstants.PARAM_BLANK,FrameworkConstants.PARAM_BLANK}); } } }
DAO
FileUploadInfoDAOImpl.java
package com.cybersoft4u.framework.persistence.pfm; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Repository; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import com.cybersoft4u.framework.domain.FileUpload; import com.cybersoft4u.framework.domain.pfm.FileUploadInfo; import com.cybersoft4u.framework.domain.utilities.FrameworkConstants; import com.cybersoft4u.framework.domain.utilities.PFMConstants; import com.cybersoft4u.framework.domain.utilities.i18NUtil; import com.cybersoft4u.framework.dto.pfm.FileUploadInfoCriteriaDTO; import com.cybersoft4u.framework.persistence.common.BaseDAOImpl; import com.cybersoft4u.framework.persistence.common.FrameworkMessageCode; import com.cybersoft4u.framework.persistence.common.PfmMessageCode; import com.cybersoft4u.framework.persistence.exception.DataAccessException; import com.cybersoft4u.framework.persistence.exception.FrameworkServiceException; import com.cybersoft4u.framework.persistence.utilities.AliasBean; import com.cybersoft4u.framework.persistence.utilities.SqlQueryBean; import com.cybersoft4u.framework.persistence.utilities.sql.SqlStatement; /** * Purpose: 上傳文檔記錄表的DAO實現 * @author: shihuangzhe.com * @since: JDK 1.6 * @date: 2011-12-28 * @MaintenancePersonnel: shihuangzhe.com */ @Repository("fileUploadInfoDAO") public class FileUploadInfoDAOImpl extends BaseDAOImpl implements FileUploadInfoDAO { /** * logger */ private static final Log logger = LogFactory.getLog(FileUploadInfoDAOImpl.class); /** * Constructor--. */ public FileUploadInfoDAOImpl() { super(); } /** * Purpose:根據條件查詢上傳文檔記錄列表(不分頁). * @author: liongao * @param fileUploadInfoCriteriaDTO * @throws DataAccessException * @return: List<FileUploadInfoDTO> */ @SuppressWarnings("unchecked") @Override public List<FileUpload> listFileUploadInfo(FileUploadInfoCriteriaDTO fileUploadInfoCriteriaDTO) throws DataAccessException { logger.info("Enter FileUploadInfoDAOImpl.listFileUploadInfo()"); try{ if(fileUploadInfoCriteriaDTO == null || (fileUploadInfoCriteriaDTO != null && !StringUtils.hasText(fileUploadInfoCriteriaDTO.getProjectNo()))) { logger.debug("FileUploadInfoDAOImpl.listFileUploadInfo() projectNo is null"); throw new DataAccessException(FrameworkMessageCode.ARGUMENT_IS_NULL); } //得到schema的名稱 String pmsSchema = this.getSchemaName(); SqlStatement sql = new SqlStatement(); // set select sql.addSelectClause("fui.identifier", "identifier");//pk sql.addSelectClause("fui.FILE_NAME", "fileName");//檔案名稱 sql.addSelectClause("fui.ALIAS_FILE_NAME", "aliasFileName");//檔案別名 sql.addSelectClause("fui.UPLOAD_DATE", "uploadDate");//上載時間 sql.addSelectClause("fui.UPLOAD_USER", "uploadUser");//上載人 sql.addSelectClause("fui.FILE_SIZE", "fileSize");//檔案大小 sql.addSelectClause("fui.COMMENTS", "comments");//附注 sql.addSelectClause("fui.LOACTION", "loaciton");//存放路徑 //set from sql.addFromExpression(pmsSchema+".PFM_FILE_UPLOAD_INFO fui "); //set where if(fileUploadInfoCriteriaDTO != null){ if(StringUtils.hasText(fileUploadInfoCriteriaDTO.getProjectNo())){ sql.addWhereClause(" fui.PROJECT_NO =:projectNo",fileUploadInfoCriteriaDTO.getProjectNo()); } if(StringUtils.hasText(fileUploadInfoCriteriaDTO.getSource())){ sql.addWhereClause(" fui.SOURCE =:source",fileUploadInfoCriteriaDTO.getSource()); } if(StringUtils.hasText(fileUploadInfoCriteriaDTO.getExtraId())){ sql.addWhereClause(" fui.EXTRA_ID =:extraId",fileUploadInfoCriteriaDTO.getExtraId()); } } //set order by sql.setOrderByExpression(" fui.UPLOAD_DATE "); SqlQueryBean sqlQueryBean = sql.createSqlQueryBean(); logger.debug(sql.toString()); AliasBean aliasBean = sql.createAliasBean(FileUpload.class); sql.clear(); List<FileUpload> fileUploadInfoList = this.getDaoSupport().findByNativeSql(sqlQueryBean, aliasBean); return fileUploadInfoList; }catch(Throwable e){ logger.error("FileUploadInfoDAOImpl.listFileUploadInfo error-->" + e.getMessage(), e); throw new DataAccessException(FrameworkMessageCode.DATA_ACCESS_FAILURE, e); } } /** * Purpose:復制檔案. * @author: liongao * @param fromPath * @param aliasFileName * @param toPath * @throws IOException * @return: long */ @Override public long copyFile(String fromPath,String aliasFileName, String toPath) throws IOException { logger.info("Enter FileUploadInfoDAOImpl.copyFile()"); long copySizes = 0; try{ //源檔案路徑 File file1=new File(fromPath); if(!file1.exists()){ logger.error("FileUploadInfoDAOImpl.copyFile() error, 源檔案不存在"); copySizes = -1; return copySizes; } //源檔案存在,才進行復制動作 //目標檔案路徑 File file2=new File(toPath); if(!file2.exists()){ file2.mkdirs(); } FileChannel fcin = new FileInputStream(file1).getChannel(); FileChannel fcout = new FileOutputStream( new File(toPath,aliasFileName)).getChannel(); long size = fcin.size(); fcin.transferTo(0,fcin.size(),fcout); fcin.close(); fcout.close(); copySizes = size; }catch (FileNotFoundException e) { logger.error("FileUploadInfoDAOImpl.copyFile error-->FileNotFoundException" + e.getMessage(), e); copySizes = -1; } catch (IOException e) { logger.error("FileUploadInfoDAOImpl.copyFile error-->IOException" + e.getMessage(), e); copySizes = -1; } return copySizes; } /** * Purpose: 移除檔案 * @author: liongao * @param realPath --服務器真實路徑 * @param tempPath --臨時路徑 * @throws IOException * @return: void */ @Override public void removeFile(String realPath,String tempPath) throws IOException { logger.info("Enter FileUploadInfoDAOImpl.removeFile()"); try{ //真實檔案路徑 File file1=new File(realPath); if(file1.exists()){ file1.delete(); } if(StringUtils.hasText(tempPath)){ //臨時檔案路徑 File file2=new File(tempPath); if(file2.exists()){ file2.delete(); } } }catch(Exception e){ logger.error("FileUploadInfoDAOImpl.removeFile error-->IOException" + e.getMessage(), e); } } /** * Purpose: 上傳檔案(復制檔案到真實路徑、寫入db). * @author: liongao * @param tempResult * @param projectNo * @param source * @param extraId * @param errCode * @throws DataAccessException * @return: String */ @Override public String uploadFileInfo(Map<Integer,FileUpload> tempResult,String projectNo,String source ,String extraId ,String errCode) throws DataAccessException { logger.info("Enter FileUploadInfoDAOImpl.uploadFileInfo()"); //是否執行成功 String isOk = FrameworkConstants.NULL_STRING; try{ if(!CollectionUtils.isEmpty(tempResult)){//不為空 if(!StringUtils.hasText(projectNo)){ logger.error("Error FileUploadInfoDAOImpl.uploadFileInfo(),Context value projectNo is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } //判断档案名称是否重复 FileUploadInfoCriteriaDTO fileUploadInfoCriteriaDTO = new FileUploadInfoCriteriaDTO(); fileUploadInfoCriteriaDTO.setProjectNo(projectNo); Map<String, String> returnResult = this.checkFileNameRepeat(projectNo, tempResult, listFileUploadInfo(fileUploadInfoCriteriaDTO)); if(!CollectionUtils.isEmpty(returnResult)){//有重名档案 for(Map.Entry<String,String> one:returnResult.entrySet()){ isOk += one.getValue()+ PFMConstants.SEPARATOR; } return isOk; } //循環map for(Map.Entry<Integer,FileUpload> oneFile:tempResult.entrySet()){ FileUploadInfo file = new FileUploadInfo(); file.setProjectNo(projectNo);//專案編號 file.setSource(source);//檔案來源 file.setFileName(oneFile.getValue().getFileName());//文件原名 file.setAliasFileName(oneFile.getValue().getAliasFileName());//文件別名 file.setUploadDate(oneFile.getValue().getUploadDate());//上傳日期 file.setUploadUser(oneFile.getValue().getUploadUser());//上傳人 file.setFileSize(oneFile.getValue().getFileSize());//檔案大小 file.setFileType(oneFile.getValue().getFileType());//檔案類別 file.setComments(oneFile.getValue().getComments());//評論 file.setExtraId(extraId);// 額外的id.用于存儲上載檔案所依附之資料identifier //復制檔案(從臨時目錄復制檔案到真實目錄) String toPath = FrameworkConstants.NULL_STRING; if(FrameworkConstants.TRUE.equals(checkSystemOS())){//windows toPath = oneFile.getValue().getLoaciton().substring(0,oneFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).substring(0,oneFile.getValue().getLoaciton().substring(0,oneFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)) + FrameworkConstants.PAGE_PARAM_SLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK; }else if(FrameworkConstants.FALSE.equals(checkSystemOS())){//Linux toPath = oneFile.getValue().getLoaciton().substring(0,oneFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).substring(0,oneFile.getValue().getLoaciton().substring(0,oneFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)) + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK; } //2.復制檔案--到服務器真實目錄 long copyFile = this.copyFile(oneFile.getValue().getLoaciton(), oneFile.getValue().getAliasFileName(), toPath); if(copyFile > 0){ //3.寫入db //循環上載檔案,并且寫入db file.setLoaciton(toPath + oneFile.getValue().getAliasFileName());//設置文件存放路徑(真實路徑) String flag = this.getDaoSupport().save(file).toString(); //執行成功 if(StringUtils.hasText(flag)){ isOk = FrameworkConstants.STR_TRUE; }else{//執行失敗後,刪除檔案 this.removeFile(toPath+oneFile.getValue().getAliasFileName(), oneFile.getValue().getLoaciton()); } } } }else{ isOk = FrameworkConstants.STR_TRUE; } return isOk; }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoDAOImpl.uploadFileInfo() error-->" + e.getMessage(), e); throw new FrameworkServiceException(PfmMessageCode.INSERT_FAILURE, new String[]{i18NUtil.getName(errCode),FrameworkConstants.PARAM_BLANK}); } catch (Exception e) { logger.error("Exception FileUploadInfoDAOImpl.uploadFileInfo() error-->" + e.getMessage(), e); throw new FrameworkServiceException(PfmMessageCode.INSERT_FAILURE, new String[]{i18NUtil.getName(errCode),FrameworkConstants.PARAM_BLANK}); } } /** * Purpose: 修改上載檔案(先刪除,後上載) * @author: liongao * @param tempResult * @param projectNo --專案編號 * @param source --檔案來源(暫時以模組填入),如:需求變更管理 crInfoModule * @param errCode --錯誤編號 * @throws DataAccessException * @return: String */ @Override public String updateUploadFileInfo(Map<Integer,FileUpload> tempResult, String projectNo, String source,String extraId, String errCode) throws DataAccessException { logger.info("Enter FileUploadInfoDAOImpl.updateUploadFileInfo()"); //是否執行成功 String isOk = FrameworkConstants.NULL_STRING; try{ if(!StringUtils.hasText(projectNo) || !StringUtils.hasText(source) || !StringUtils.hasText(extraId) ){ logger.error("Error FileUploadInfoDAOImpl.updateUploadFileInfo(),Context value projectNo or source or extraId is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } //根據項目編號,從資料庫中查詢出上載列表,與session中有標記之資料進行比對 FileUploadInfoCriteriaDTO fileUploadInfoCriteriaDTO = new FileUploadInfoCriteriaDTO(); fileUploadInfoCriteriaDTO.setProjectNo(projectNo);//項目編號 fileUploadInfoCriteriaDTO.setSource(source);//檔案來源 fileUploadInfoCriteriaDTO.setExtraId(extraId);//額外的id.用于存儲上載檔案所依附之資料identifier List<FileUpload> lists = this.listFileUploadInfo(fileUploadInfoCriteriaDTO); if(CollectionUtils.isEmpty(lists)){//資料庫為空,則直接結束 isOk = FrameworkConstants.STR_TRUE; } //建立臨時list,用與存儲session中取得的(不需要)上載列表(標記不為false的,也就是說,是之前從db中查詢出來的) List<FileUpload> temList = new ArrayList<FileUpload>(); //建立臨時list,用于存儲session中(需要)上載的列表(標記為false)。主要用于校驗檔案名稱重復問題 Map<Integer,FileUpload> needUploadLists = new LinkedHashMap<Integer,FileUpload>(); //--------------------------------------start--校驗檔案名稱重復--------------------------------------------------- if(!tempResult.isEmpty()){ //循環map for(Map.Entry<Integer,FileUpload> checkFile:tempResult.entrySet()){ if(!checkFile.getValue().isFlag()){//為false,則表明是需要新上載的檔案 needUploadLists.put(checkFile.getKey(), checkFile.getValue()); }else{//不需要上傳之檔案列表(從db中查詢出來的) FileUpload file = new FileUpload(); file.setProjectNo(projectNo);//專案編號 file.setSource(source);//檔案來源 file.setFileName(checkFile.getValue().getFileName());//文件原名 file.setAliasFileName(checkFile.getValue().getAliasFileName());//文件別名 file.setUploadDate(checkFile.getValue().getUploadDate());//上傳日期 file.setUploadUser(checkFile.getValue().getUploadUser());//上傳人 file.setFileSize(checkFile.getValue().getFileSize());//檔案大小 file.setFileType(checkFile.getValue().getFileType());//檔案類別 file.setComments(checkFile.getValue().getComments());//評論 file.setExtraId(extraId);// 額外的id.用于存儲上載檔案所依附之資料identifier temList.add(file); } } } //--------------------------------------end--校驗檔案名稱重復----------------------------------------------------- //比對lists與templist,確定資料庫中需要刪除的上傳檔案 if(!CollectionUtils.isEmpty(lists) && !CollectionUtils.isEmpty(temList)){ int size = temList.size(); for(int i = 0; i< size;i ++){ for(int j = 0;j< lists.size();j++){ if(temList.get(i).getFileName().equals(lists.get(j).getFileName())){ lists.remove(j); } } } } //如果lists不為空,則去資料庫循環刪除上傳資料 if(!CollectionUtils.isEmpty(lists)){ int size = lists.size(); for(int i = 0;i < size;i++){ FileUpload file = (FileUpload)lists.get(i); //從資料庫中刪除檔案 this.daoSupport.delete(file.getIdentifier(), FileUploadInfo.class); //并且從硬盤上刪除檔案 this.removeFile(file.getLoaciton(), null); isOk = FrameworkConstants.STR_TRUE; } }else if(CollectionUtils.isEmpty(lists)){//無需要刪除之檔案資料 isOk = FrameworkConstants.STR_TRUE; } //結果不為空,則校驗檔案名稱 if(!CollectionUtils.isEmpty(needUploadLists)){ //根據項目編號,重新從資料庫中查詢最新的檔案列表(跟需要上載的檔案做比對) FileUploadInfoCriteriaDTO fileUploadInfoCriteriaDTO2 = new FileUploadInfoCriteriaDTO(); fileUploadInfoCriteriaDTO2.setProjectNo(projectNo);//項目編號 fileUploadInfoCriteriaDTO2.setSource(source);//檔案來源 fileUploadInfoCriteriaDTO2.setExtraId(extraId);//額外的id.用于存儲上載檔案所依附之資料identifier List<FileUpload> lists2 = this.listFileUploadInfo(fileUploadInfoCriteriaDTO2); //從資料庫中查詢出的資料中拿掉已經刪除的資料 if(!CollectionUtils.isEmpty(lists2) && !CollectionUtils.isEmpty(lists)){ int size = lists.size(); for(int i = 0; i< size;i ++){ for(int j = 0;j< lists2.size();j++){ if(lists.get(i).getFileName().equals(lists2.get(j).getFileName())){ lists2.remove(j); } } } } //校驗檔案名稱重復 Map<String, String> returnResult = this.checkFileNameRepeat(projectNo, needUploadLists, lists2); if(!CollectionUtils.isEmpty(returnResult)){ isOk = "";//重置 for(Map.Entry<String,String> one:returnResult.entrySet()){ isOk += one.getValue()+ PFMConstants.SEPARATOR; } return isOk; } //校驗通過後,則上載新檔案 for(Map.Entry<Integer,FileUpload> uploadFile:needUploadLists.entrySet()){ FileUploadInfo file = new FileUploadInfo(); file.setProjectNo(projectNo);//專案編號 file.setSource(source);//檔案來源 file.setFileName(uploadFile.getValue().getFileName());//文件原名 file.setAliasFileName(uploadFile.getValue().getAliasFileName());//文件別名 file.setUploadDate(uploadFile.getValue().getUploadDate());//上傳日期 file.setUploadUser(uploadFile.getValue().getUploadUser());//上傳人 file.setFileSize(uploadFile.getValue().getFileSize());//檔案大小 file.setFileType(uploadFile.getValue().getFileType());//檔案類別 file.setComments(uploadFile.getValue().getComments());//評論 file.setExtraId(extraId);// 額外的id.用于存儲上載檔案所依附之資料identifier //復制檔案(從臨時目錄復制檔案到真實目錄) String toPath = FrameworkConstants.NULL_STRING; if(FrameworkConstants.TRUE.equals(checkSystemOS())){//windows toPath = uploadFile.getValue().getLoaciton().substring(0,uploadFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).substring(0,uploadFile.getValue().getLoaciton().substring(0,uploadFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).lastIndexOf(FrameworkConstants.PAGE_PARAM_SLASH_MARK)) + FrameworkConstants.PAGE_PARAM_SLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_SLASH_MARK; }else if(FrameworkConstants.FALSE.equals(checkSystemOS())){//Linux toPath = uploadFile.getValue().getLoaciton().substring(0,uploadFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).substring(0,uploadFile.getValue().getLoaciton().substring(0,uploadFile.getValue().getLoaciton().indexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK +FrameworkConstants.TEMP_UPLOAD_FOLDER_PATH)).lastIndexOf(FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK)) + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK + FrameworkConstants.UPLOAD_FOLDER_PATH + FrameworkConstants.PAGE_PARAM_BACKSLASH_MARK; } //2.復制檔案 long copyFile = this.copyFile(uploadFile.getValue().getLoaciton(), uploadFile.getValue().getAliasFileName(), toPath); if(copyFile > 0){ //3.寫入db //循環上載檔案,并且寫入db file.setLoaciton(toPath + uploadFile.getValue().getAliasFileName());//設置文件存放路徑(真實路徑) String flag = this.getDaoSupport().save(file).toString(); //執行成功 if(StringUtils.hasText(flag)){ isOk = FrameworkConstants.STR_TRUE; }else{//執行失敗後,刪除檔案 this.removeFile(toPath+uploadFile.getValue().getAliasFileName(), uploadFile.getValue().getLoaciton()); } } } } }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoDAOImpl.uploadFileInfo() error-->" + e.getMessage(), e); throw new FrameworkServiceException(PfmMessageCode.UPDATE_FAILURE, new String[]{i18NUtil.getName(errCode),FrameworkConstants.PARAM_BLANK}); } catch (Exception e) { logger.error("Exception FileUploadInfoDAOImpl.uploadFileInfo() error-->" + e.getMessage(), e); throw new FrameworkServiceException(PfmMessageCode.UPDATE_SUCCESS, new String[]{i18NUtil.getName(errCode),FrameworkConstants.PARAM_BLANK}); } return isOk; } /** * Purpose: 上傳檔案列表list轉map列表 * @author: liongao * @param files * @throws DataAccessException * @return: Map<String,FileUpload> */ @Override public Map<Integer,FileUpload> changeUploadFileListToMap(List<FileUpload> files) throws DataAccessException { logger.info("Enter FileUploadInfoDAOImpl.changeUploadFileListToMap()"); Map<Integer,FileUpload> fileList = new LinkedHashMap<Integer,FileUpload>(); try{ if(!CollectionUtils.isEmpty(files)){ int size = files.size(); for(int i=0;i<size;i++){ //格式化日期 SimpleDateFormat sf =new SimpleDateFormat(FrameworkConstants.DT_FMT_YYYYMMDD_SLASH); FileUpload fileUploadInfoDTO = (FileUpload)files.get(i); FileUpload f = new FileUpload(); f.setAliasFileName(fileUploadInfoDTO.getAliasFileName()); f.setComments(fileUploadInfoDTO.getComments() == null?"":fileUploadInfoDTO.getComments()); f.setFileName(fileUploadInfoDTO.getFileName()); f.setFileNo(fileUploadInfoDTO.getFileNo()); f.setFileSize(fileUploadInfoDTO.getFileSize()); f.setFileType(fileUploadInfoDTO.getFileSize()); f.setFlag(true); f.setLoaciton(fileUploadInfoDTO.getLoaciton()); f.setProjectNo(fileUploadInfoDTO.getProjectNo()); f.setSource(fileUploadInfoDTO.getSource()); f.setUploadDate(fileUploadInfoDTO.getUploadDate()); f.setStrUploadDate(sf.format(fileUploadInfoDTO.getUploadDate())); f.setUploadUser(fileUploadInfoDTO.getUploadUser()); f.setFileNo(i); fileList.put(i, f); } } return fileList; }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoDAOImpl.changeUploadFileListToMap() error-->" + e.getMessage(), e); } catch (Exception e) { logger.error("Exception FileUploadInfoDAOImpl.changeUploadFileListToMap() error-->" + e.getMessage(), e); } return fileList; } /** * Purpose: 根據項目編號、檔案來源、額外id刪除檔案信息. * @author: liongao * @param projectNo * @throws DataAccessException * @return: boolean */ @Override public boolean deleteFileinfoByProjectNoSourceExtraId(String projectNo ,String source,String extraId) throws DataAccessException { logger.info("Enter FileUploadInfoDAOImpl.deleteFileinfoByProjectNo()"); boolean flag = false; try{ if(!StringUtils.hasText(projectNo) || !StringUtils.hasText(source) || !StringUtils.hasText(extraId)){ logger.error("Error FileUploadInfoDAOImpl.deleteFileinfoByProjectNo(),Context value projectNo or source or extraId is null!"); throw new FrameworkServiceException(FrameworkMessageCode.INCORRECT_PARAMATER); } //get lists FileUploadInfoCriteriaDTO fileUploadInfoCriteriaDTO = new FileUploadInfoCriteriaDTO(); fileUploadInfoCriteriaDTO.setProjectNo(projectNo); fileUploadInfoCriteriaDTO.setSource(source); fileUploadInfoCriteriaDTO.setExtraId(extraId); List<FileUpload> files = this.listFileUploadInfo(fileUploadInfoCriteriaDTO); if(CollectionUtils.isEmpty(files)){//無資料,則直接返回true flag = true; return flag; } //得到schema的名稱 String pmsSchema = this.getSchemaName(); //sql2 String sql2 = "DELETE FROM "+ pmsSchema +".PFM_FILE_UPLOAD_INFO pfui" + " WHERE pfui.PROJECT_NO = :projectNo "; sql2 += " AND pfui.SOURCE = :source"; sql2 += " AND pfui.EXTRA_ID = :extraId"; SqlQueryBean sqlQueryBean2 = new SqlQueryBean(sql2); sqlQueryBean2.setParameter("projectNo", projectNo); sqlQueryBean2.setParameter("source", source); sqlQueryBean2.setParameter("extraId", extraId); int result = super.getDaoSupport().updateByNativeSql(sqlQueryBean2); if(result > 0){ flag = true; } //刪除硬盤上的檔案 if(flag){ int size = files.size(); FileUpload file = null; for(int i = 0;i < size; i++){ file = files.get(i); this.removeFile(file.getLoaciton(), null); } } return flag; }catch (FrameworkServiceException e) { logger.error("Error FrameworkServiceException FileUploadInfoDAOImpl.changeUploadFileListToMap() error-->" + e.getMessage(), e); } catch (Exception e) { logger.error("Exception FileUploadInfoDAOImpl.changeUploadFileListToMap() error-->" + e.getMessage(), e); } return flag; } /** * Purpose: 校驗檔案名稱重復(跟db比對). * @author: liongao * @param projectNo --專案編號 * @param fileLists --檔案列表(session中取得的) * @param dbFiles --檔案列表(db中的) * @throws DataAccessException * @return: Map<String,String> */ @Override public Map<String, String> checkFileNameRepeat(String projectNo, Map<Integer, FileUpload> fileLists, List<FileUpload> dbFiles) throws DataAccessException { Map<String, String> result = new HashMap<String,String>(); try{ if(fileLists == null){ return null; } if(dbFiles == null){ return null; } int size = dbFiles.size(); for(Map.Entry<Integer,FileUpload> oneFile:fileLists.entrySet()){ for(int i = 0;i < size; i++){ if(oneFile.getValue().getFileName().equals(dbFiles.get(i).getFileName())){ result.put(oneFile.getValue().getFileName(), oneFile.getValue().getFileName()); } } } }catch(Exception e){ logger.error("Exception FileUploadInfoDAOImpl.checkFileNameRepeat() error-->" + e.getMessage(), e); } return result; } /** * Purpose: 判斷os是linux還是windows * @author: liongao * @return: String */ public String checkSystemOS(){ String returnStr = FrameworkConstants.NULL_STRING; try{ //判斷os是windows還是linux Properties prop = System.getProperties(); String os = prop.getProperty(FrameworkConstants.OS_NAME); String sysWin = FrameworkConstants.WINDOWS_SYSTEM; String sysLinux = FrameworkConstants.LINUX_SYSTEM; if(os.toLowerCase().indexOf(sysWin) != -1){//windows returnStr = FrameworkConstants.TRUE; }else if(os.toLowerCase().equals(sysLinux)){//Linux returnStr = FrameworkConstants.FALSE; } }catch(Exception e){ logger.error("Exception FileUploadInfoDAOImpl.checkSystemOS() error-->" + e.getMessage(), e); } return returnStr; } }