<%@ page import="java.io.File" %> <%@ page import="java.io.IOException" %> <%@ page import="java.io.PrintWriter" %> <%@ page import="java.io.UnsupportedEncodingException" %> <%@ page import="java.util.HashMap" %> <%@ page import="java.util.Iterator" %> <%@ page import="java.util.List" %> <%@ page import="org.apache.commons.fileupload.FileItem" %> <%@ page import="org.apache.commons.fileupload.FileUploadException" %> <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %> <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %> <%@ page import="org.apache.commons.io.FilenameUtils" %> <%@ page import="org.apache.log4j.Logger" %> <%! // create logging object Logger logger = Logger.getLogger(getClass()); // Define WebFileManager(WFM) Constant String WFM_DATA_DEL = String.valueOf((char)0x1A); // data delimeter String WFM_DATASTART_DEL = String.valueOf((char)0x1C); // data start indicator String WFM_DATAEND_DEL = String.valueOf((char)0x1F); // data end indicator int maxMemoryFileSize = 10; // maximum memory file size int maxFileSize = 1000 * 1024 * 1024; // maximum file size (100MB) String errorMsg = ""; String contextRootDir = ""; String tempDirAbsolutePath = ""; String saveBaseDirAbsolutePath = ""; %> <% ServletFileUpload uplaodHandler = null; // file uplaod handler List fileItemList = null; // file item list FileItem fileItem = null; // file item HashMap paramMap = new HashMap(); // parameter map String strResultMsg = WFM_DATASTART_DEL; out.clearBuffer(); logger.info("=============================================================="); logger.info("webfilemanager upload start"); // Set cross domain response header response.setHeader("Access-Control-Allow-Credentials", "true"); if (request == null) { logger.error("Access-Control-Allow-Origin = *"); response.setHeader("Access-Control-Allow-Origin", "*"); } else { logger.error("Access-Control-Allow-Origin = " + request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); } response.setHeader("Access-Control-Allow-Headers", "X-Requested-With"); // Set upload file temp dir, save base dir path // setUploadEnvSetting(getServletContext()); // servlet 3.0 spec setUploadEnvSetting(request.getSession().getServletContext()); // Check whether the request has multipart data content. boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { try { logger.error("There is no multipart data in request"); strResultMsg += getErrorMsg("", "There is no multipart data in request"); strResultMsg += WFM_DATAEND_DEL; out.print(strResultMsg); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return; } // Create a file upload handler uplaodHandler = getFileUploadProcessor(); logger.info("Success to create a file upload handler"); // parse the request try { fileItemList = uplaodHandler.parseRequest(request); } catch (FileUploadException ex) { try { logger.error("Fail to parse a request"); strResultMsg += getErrorMsg("", "Fail to parse a request"); strResultMsg += WFM_DATAEND_DEL; out.print(strResultMsg); } catch (UnsupportedEncodingException e) { logger.error("Exception msg = " + e.getMessage()); e.printStackTrace(); } return; } logger.info("Success to parse a request"); // Process the parameter Iterator iter1 = fileItemList.iterator(); while (iter1.hasNext()) { fileItem = (FileItem)iter1.next(); // process a regular form field if (fileItem.isFormField()) { String fieldName = fileItem.getFieldName(); String fieldValue = fileItem.getString("UTF-8"); logger.info("fieldName = " + fieldName + ", fieldValue = " + fieldValue); paramMap.put(fieldName, fieldValue); } } Iterator iter2 = fileItemList.iterator(); while (iter2.hasNext()) { fileItem = (FileItem)iter2.next(); // process a regular form field if (fileItem.isFormField()) { continue; } String fileItemFileName = fileItem.getName(); String fileResultMsg = null; try { // process a upload multipart data String saveFileName = handleUploadFile(fileItem, paramMap); if (saveFileName == null) { fileResultMsg = getErrorMsg(fileItemFileName, errorMsg); } else { // make a success message fileResultMsg = getSuccessMsg(fileItemFileName, saveFileName); } logger.info("fileResultMsg = [" + fileResultMsg + "]"); // add one file process message to return message strResultMsg += fileResultMsg; } catch (Exception ex) { logger.error("Exception Msg = " + ex.getMessage()); ex.printStackTrace(); fileResultMsg = getErrorMsg(fileItemFileName, "Fail to process upload file."); // add one file process message to return message strResultMsg += fileResultMsg; } } // add data end delimiter strResultMsg += WFM_DATAEND_DEL; logger.info("strResultMsg = [" + strResultMsg + "]"); out.print(strResultMsg); %> <%! // Set upload file temp dir, save base dir path public void setUploadEnvSetting(ServletContext context) { // get context real path contextRootDir = context.getRealPath("/"); if(contextRootDir.endsWith(File.separator) == false) { contextRootDir += File.separator; } // temporary directory absolute path for temporary file tempDirAbsolutePath = contextRootDir + "temp"; saveBaseDirAbsolutePath = contextRootDir + "upload"; logger.info("tempDirAbsolutePath = " + tempDirAbsolutePath); logger.info("saveBaseDirAbsolutePath = " + saveBaseDirAbsolutePath); makeDirUsingDirPath(tempDirAbsolutePath); makeDirUsingDirPath(saveBaseDirAbsolutePath); return; } // handle a upload file data public String handleUploadFile(FileItem fileItem, HashMap paramMap) throws Exception { String saveFileAbsolutePath = ""; // file absolute path to save String saveFileName = ""; String filePath = fileItem.getName(); // HTML File Item Name String fileName = FilenameUtils.getName(filePath); // file name String paramDirPath = ""; String paramFileName = ""; logger.info("filePath = " + filePath); logger.info("fileName = " + fileName); logger.info("getContentType = " + fileItem.getContentType()); logger.info("getSize = " + fileItem.getSize()); // get file save information paramDirPath = paramMap.get("DIR_PATH") == null ? "" : (String)paramMap.get("DIR_PATH"); paramFileName = paramMap.get("FILE_NAME") == null ? "" : (String)paramMap.get("FILE_NAME"); logger.info("paramDirPath = [" + paramDirPath + "]"); logger.info("paramFileName = [" + paramFileName + "]"); // set save directory absolute path saveFileAbsolutePath = saveBaseDirAbsolutePath; if (paramDirPath.length() > 0) { saveFileAbsolutePath = saveFileAbsolutePath + File.separatorChar + paramDirPath; } // set save file absolute path if (paramFileName.length() > 0) { saveFileName = paramFileName; } else { saveFileName = fileName; } saveFileAbsolutePath = saveFileAbsolutePath + File.separator + saveFileName; logger.info("saveFileAbsolutePath = " + saveFileAbsolutePath); // make a directory for file path makeDirUsingFilePath(saveFileAbsolutePath); // save a upload file to a save file absolute path while (true) { int retryCount = 0; try { fileItem.write(new File(saveFileAbsolutePath)); break; } catch(Exception e) { logger.error("Exception Msg = " + e.getMessage()); retryCount++; if (retryCount > 5) { logger.error("Fail to wirte a file"); errorMsg = "Fail to wirte a file"; return null; } else { try { Thread.sleep(1000); } catch (InterruptedException ignore) { ; } continue; } } } logger.info("Success To Wirte File, saveFileName = " + saveFileName); // delete a file item content fileItem.delete(); // return a saved file name return saveFileName; } //TODO: change a character set of message public String msgCharacterSetConvert(String message) throws UnsupportedEncodingException { if (message == null) { return ""; } /* logger.info("don't change character set"); return message; */ logger.info("change character set UTF-8 -> ISO-8859-1"); return new String(message.getBytes("UTF-8"), "ISO-8859-1"); } // make a success message public String getSuccessMsg(String fileName, String saveFileName) throws UnsupportedEncodingException { StringBuffer returnMsg = new StringBuffer(); returnMsg.append("Result=\"success\"&"); returnMsg.append("FileName=\"" + fileName + "\"&"); returnMsg.append("SaveFileName=\"" + saveFileName + "\""); returnMsg.append(WFM_DATA_DEL); return msgCharacterSetConvert(returnMsg.toString()); } // make a error message public String getErrorMsg(String fileName, String errorMsg) throws UnsupportedEncodingException { StringBuffer returnMsg = new StringBuffer(); returnMsg.append("Result=\"error\"&"); returnMsg.append("FileName=\"" + fileName + "\"&"); returnMsg.append("Message=\"" + errorMsg + "\""); returnMsg.append(WFM_DATA_DEL); return msgCharacterSetConvert(returnMsg.toString()); } private String getRandomFileName() { return java.util.UUID.randomUUID().toString().replace("-", ""); } // get a file upload process private ServletFileUpload getFileUploadProcessor() { // create a new file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); // create a new file object for a temporary directory File tempDir = new File(tempDirAbsolutePath); // create a temporary directory if(!tempDir.exists()) { tempDir.mkdirs(); } // set a temporary directory factory.setRepository(tempDir); // set a maximum memory file size factory.setSizeThreshold(maxMemoryFileSize); // create a servlet file upload object using a factory ServletFileUpload upload = new ServletFileUpload(factory); // set a maixmum file size upload.setSizeMax(maxFileSize); // set header encoding characterset for hangul file name upload.setHeaderEncoding("UTF-8"); return upload; } // make a directory using a file path public void makeDirUsingFilePath(String fileAbsolutePath) { File oFile = new File(fileAbsolutePath); File oDir = oFile.getParentFile(); // create a diectory if (!oDir.exists()) { oDir.mkdirs(); } } // make a directory using a dir path public void makeDirUsingDirPath(String dirAbsolutePath) { File oDir = new File(dirAbsolutePath); // create a diectory if (!oDir.exists()) { oDir.mkdirs(); } } %>