List of usage examples for org.apache.commons.fileupload DiskFileUpload parseRequest
public List parseRequest(HttpServletRequest req) throws FileUploadException
From source file:oscar.DocumentMgtUploadServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { formatter = new SimpleDateFormat("yyyyMMddHmmss"); today = new java.util.Date(); output = formatter.format(today);//from w w w . j a v a 2 s . c o m String foldername = "", fileheader = "", forwardTo = ""; // Get properties from oscar_mcmaster.properties Properties ap = OscarProperties.getInstance(); forwardTo = ap.getProperty("DOC_FORWARD"); foldername = ap.getProperty("DOCUMENT_DIR"); if (forwardTo == null || forwardTo.length() < 1) return; // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); try { // Parse the request List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //String name = item.getFieldName(); //String value = item.getString(); } else { String pathName = item.getName(); String[] fullFile = pathName.split("[/|\\\\]"); File savedFile = new File(foldername, output + fullFile[fullFile.length - 1]); fileheader = output + fullFile[fullFile.length - 1]; item.write(savedFile); } } } catch (FileUploadException e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } catch (Exception e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } /* ServletInputStream sis = request.getInputStream(); BufferedOutputStream dest = null; FileOutputStream fos = null; boolean bwri = false; boolean bfbo = true; boolean benddata = false; boolean bf = false; byte boundary[] = temp.getBytes(); while (bf?true:((count = sis.readLine(data, 0, BUFFER)) != -1)) { bf = false; benddata = false; if(count==2 && data[0]==13 && data[1]==10) { enddata[0] = 13; enddata[1] = 10; for(int i=0;i<BUFFER;i++) data[i]=0; count = sis.readLine(data, 0, BUFFER); if(count==2 && data[0]==13 && data[1]==10) { dest.write(enddata, 0, 2); bf = true; continue; } else { benddata = true; } } String s = new String(data,2,temp.length()); if(temp.equals(s)) { if(benddata) break; if((c =sis.readLine(data1, 0, BUFFER)) != -1) { filename = new String(data1); if(filename.length()>2 && filename.indexOf("filename")!=-1) { filename = filename.substring(filename.lastIndexOf("filename=\"") + "filename\"".length() +1, filename.lastIndexOf('"')); filename = filename.substring(filename.lastIndexOf('\\')+1, filename.length()); fileheader = output + filename; fos = new FileOutputStream(foldername+ output + filename); dest = new BufferedOutputStream(fos, BUFFER); } c =sis.readLine(data2, 0, BUFFER); if((c =sis.readLine(data2, 0, BUFFER)) != -1) { bwri = bfbo?true:false; } } bfbo = bfbo?false:true; for(int i=0;i<BUFFER;i++) data[i]=0; continue; } //end period if(benddata) { benddata = false; dest.write(enddata, 0, 2); for(int i=0;i<2;i++) enddata[i]=0; } if(bwri) { dest.write(data, 0, count); for(int i=0;i<BUFFER;i++) data[i]=0; } } //end while //dest.flush(); fos.close(); dest.close(); sis.close(); */ DocumentBean documentBean = new DocumentBean(); request.setAttribute("documentBean", documentBean); documentBean.setFilename(fileheader); // documentBean.setFileDesc(filedesc); // documentBean.setFoldername(foldername); // documentBean.setFunction(function); // documentBean.setFunctionID(function_id); // documentBean.setCreateDate(fileheader); // documentBean.setDocCreator(creator); // Call the output page. RequestDispatcher dispatch = getServletContext().getRequestDispatcher(forwardTo); dispatch.forward(request, response); }
From source file:oscar.DocumentUploadServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String foldername = "", fileheader = "", forwardTo = ""; forwardTo = OscarProperties.getInstance().getProperty("RA_FORWORD"); foldername = OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); String inboxFolder = OscarProperties.getInstance().getProperty("ONEDT_INBOX"); String archiveFolder = OscarProperties.getInstance().getProperty("ONEDT_ARCHIVE"); if (forwardTo == null || forwardTo.length() < 1) return;//from www . j a v a 2 s. co m String providedFilename = request.getParameter("filename"); if (providedFilename != null) { File documentDirectory = new File(foldername); File providedFile = new File(inboxFolder, providedFilename); if (!providedFile.exists()) { providedFile = new File(archiveFolder, providedFilename); } FileUtils.copyFileToDirectory(providedFile, documentDirectory); fileheader = providedFilename; } else { DiskFileUpload upload = new DiskFileUpload(); try { // Parse the request @SuppressWarnings("unchecked") List<FileItem> /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { // } else { String pathName = item.getName(); String[] fullFile = pathName.split("[/|\\\\]"); File savedFile = new File(foldername, fullFile[fullFile.length - 1]); fileheader = fullFile[fullFile.length - 1]; item.write(savedFile); if (OscarProperties.getInstance().isPropertyActive("moh_file_management_enabled")) { FileUtils.copyFileToDirectory(savedFile, new File(inboxFolder)); } } } } catch (FileUploadException e) { MiscUtils.getLogger().error("Error", e); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } } DocumentBean documentBean = new DocumentBean(); request.setAttribute("documentBean", documentBean); documentBean.setFilename(fileheader); RequestDispatcher dispatch = getServletContext().getRequestDispatcher(forwardTo); dispatch.forward(request, response); }
From source file:oscar.eform.upload.UploadImage.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String foldername = "", fileheader = ""; Properties ap = OscarProperties.getInstance(); foldername = ap.getProperty("eform_image"); // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); try {/*from w w w. ja v a2s. c o m*/ // Parse the request List items = upload.parseRequest(request); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //String name = item.getFieldName(); //String value = item.getString(); } else { String pathName = item.getName(); String[] fullFile = pathName.split("[/|\\\\]"); File savedFile = new File(foldername, fullFile[fullFile.length - 1]); fileheader = fullFile[fullFile.length - 1]; MiscUtils.getLogger().debug(fileheader + "uploaded to \n" + foldername); item.write(savedFile); } } } catch (FileUploadException e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } catch (Exception e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } // Call the output page. PrintWriter out = response.getWriter(); out.println("<head>"); out.println("<script language=\"JavaScript\">"); out.println("setTimeout(\"top.location.href = '../eform/uploadimages.jsp'\",1000);"); out.println("</script>"); out.println("</head>"); out.println("<body>"); out.println("File upload successfully.<br> Please wait for 1 seconds to go to \"modify\" page"); out.println("</body>"); }
From source file:oscar.oscarBilling.ca.bc.MSP.DocumentTeleplanReportUploadServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { byte data[] = new byte[BUFFER]; byte data1[] = new byte[BUFFER / 2]; byte data2[] = new byte[BUFFER / 2]; byte enddata[] = new byte[2]; HttpSession session = request.getSession(true); String backupfilepath = ((String) session.getAttribute("homepath")) != null ? ((String) session.getAttribute("homepath")) : "null"; String foldername = "", fileheader = "", forwardTo = ""; String userHomePath = System.getProperty("user.home", "user.dir"); MiscUtils.getLogger().debug(userHomePath); Properties ap = OscarProperties.getInstance(); forwardTo = ap.getProperty("TA_FORWARD"); foldername = ap.getProperty("DOCUMENT_DIR"); ///*from w w w. j a va 2 s.co m*/ if (forwardTo == null || forwardTo.length() < 1) return; // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); try { // Parse the request List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //String name = item.getFieldName(); //String value = item.getString(); } else { String pathName = item.getName(); String[] fullFile = pathName.split("[/|\\\\]"); File savedFile = new File(foldername, fullFile[fullFile.length - 1]); fileheader = fullFile[fullFile.length - 1]; item.write(savedFile); } } } catch (FileUploadException e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } catch (Exception e) { // TODO Auto-generated catch block MiscUtils.getLogger().error("Error", e); } // // function = request.getParameter("function"); // function_id = request.getParameter("functionid"); // filedesc = request.getParameter("filedesc"); // creator = request.getParameter("creator"); /* ServletInputStream sis = request.getInputStream(); BufferedOutputStream dest = null; FileOutputStream fos = null; boolean bwri = false; boolean bfbo = true; boolean benddata = false; boolean bf = false; byte boundary[] = temp.getBytes(); while (bf?true:((count = sis.readLine(data, 0, BUFFER)) != -1)) { bf = false; benddata = false; if(count==2 && data[0]==13 && data[1]==10) { enddata[0] = 13; enddata[1] = 10; for(int i=0;i<BUFFER;i++) data[i]=0; count = sis.readLine(data, 0, BUFFER); if(count==2 && data[0]==13 && data[1]==10) { dest.write(enddata, 0, 2); bf = true; continue; } else { benddata = true; } } String s = new String(data,2,temp.length()); if(temp.equals(s)) { if(benddata) break; if((c =sis.readLine(data1, 0, BUFFER)) != -1) { filename = new String(data1); if(filename.length()>2 && filename.indexOf("filename")!=-1) { filename = filename.substring(filename.lastIndexOf('\\')+1,filename.lastIndexOf('\"')); fileheader = filename; fos = new FileOutputStream(foldername+ filename); dest = new BufferedOutputStream(fos, BUFFER); } c =sis.readLine(data2, 0, BUFFER); if((c =sis.readLine(data2, 0, BUFFER)) != -1) { bwri = bfbo?true:false; } } bfbo = bfbo?false:true; for(int i=0;i<BUFFER;i++) data[i]=0; continue; } //end period if(benddata) { benddata = false; dest.write(enddata, 0, 2); for(int i=0;i<2;i++) enddata[i]=0; } if(bwri) { dest.write(data, 0, count); for(int i=0;i<BUFFER;i++) data[i]=0; } } //end while //dest.flush(); dest.close(); sis.close(); */ DocumentBean documentBean = new DocumentBean(); request.setAttribute("documentBean", documentBean); documentBean.setFilename(fileheader); // documentBean.setFileDesc(filedesc); // documentBean.setFoldername(foldername); // documentBean.setFunction(function); // documentBean.setFunctionID(function_id); // documentBean.setCreateDate(fileheader); // documentBean.setDocCreator(creator); // Call the output page. RequestDispatcher dispatch = getServletContext().getRequestDispatcher(forwardTo); dispatch.forward(request, response); }
From source file:ro.finsiel.eunis.admin.EUNISUploadServlet.java
/** * Overrides public method doPost of javax.servlet.http.HttpServlet. * * @param request/*from w w w. j ava 2 s. c om*/ * Request object * @param response * Response object. */ public void doPost(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(false); sessionManager = (SessionManager) session.getAttribute("SessionManager"); // Initialise the default settings try { BASE_DIR = getServletContext().getInitParameter(Constants.APP_HOME_INIT_PARAM); TEMP_DIR = BASE_DIR + getServletContext().getInitParameter("TEMP_DIR"); } catch (Exception ex) { ex.printStackTrace(); } List items = new ArrayList(); boolean isMultipart = FileUpload.isMultipartContent(request); DiskFileUpload upload = new DiskFileUpload(); upload.setSizeThreshold(MAX_MEM_TRESHOLD); upload.setSizeMax(MAX_FILE_SIZE); upload.setRepositoryPath(TEMP_DIR); try { items = upload.parseRequest(request); } catch (FileUploadException ex) { ex.printStackTrace(); try { response.sendRedirect("related-reports-error.jsp?status=Error while interpreting request"); } catch (IOException _ex) { _ex.printStackTrace(); } } // If it's a multi-part content then it's an upload. So we process it. if (isMultipart) { int uploadType = -1; String description = ""; // Description of the uploaded document (used only for UPLOAD_TYPE_FILE) // Process the uploaded items for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { // FORM FIELD String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (null != fieldName && fieldName.equals("uploadType")) { if (null != fieldValue && fieldValue.equalsIgnoreCase("file")) { uploadType = UPLOAD_TYPE_FILE; } if (null != fieldValue && fieldValue.equalsIgnoreCase("picture")) { uploadType = UPLOAD_TYPE_PICTURE; } } // Id object if (null != fieldName && fieldName.equalsIgnoreCase("idobject")) { natureObjectInfo.idObject = fieldValue; } // Description if (null != fieldName && fieldName.equalsIgnoreCase("description")) { natureObjectInfo.description = fieldValue; description = fieldValue; } // Nature object type if (null != fieldName && fieldName.equalsIgnoreCase("natureobjecttype")) { natureObjectInfo.natureObjectType = fieldValue; } } } if (uploadType == UPLOAD_TYPE_FILE) { String message = ""; if (sessionManager.isAuthenticated() && sessionManager.isUpload_reports_RIGHT()) { try { uploadDocument(items, message, sessionManager.getUsername(), description); response.sendRedirect("related-reports-upload.jsp?message=" + message); } catch (IOException ex) { // Thrown by sendRedirect ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); try { String errorURL = "related-reports-error.jsp?status=" + ex.getMessage(); response.sendRedirect(errorURL); // location is a dummy param } catch (IOException ioex) { ioex.printStackTrace(); } } } else { message = "You must be logged in and have the 'upload files' "; message += "right in order to use this feature. Upload is not possible."; try { response.sendRedirect("related-reports-error.jsp?status=" + message); } catch (Exception ex) { ex.printStackTrace(); } } } if (uploadType == UPLOAD_TYPE_PICTURE) { if (sessionManager.isAuthenticated() && sessionManager.isUpload_pictures_RIGHT()) { try { uploadPicture(items); String redirectStr = "pictures-upload.jsp?operation=upload"; redirectStr += "&idobject=" + natureObjectInfo.idObject; redirectStr += "&natureobjecttype=" + natureObjectInfo.natureObjectType; redirectStr += "&filename=" + natureObjectInfo.filename; redirectStr += "&message=Picture successfully loaded."; response.sendRedirect(redirectStr); } catch (IOException ex) { // Thrown by sendRedirect ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); try { response.sendRedirect( "related-reports-error.jsp?status=An error ocurred during picture upload. " + ex.getMessage()); } catch (IOException ioex) { ioex.printStackTrace(); } } } else { try { response.sendRedirect( "related-reports-error.jsp?status=You do not have the proper rights. Upload is not possible."); } catch (IOException ex) { ex.printStackTrace(); } } } } }
From source file:sos.settings.SOSSettingsDialog.java
private void checkRequest() throws Exception { this.debug(3, "checkRequest"); this.settings.sources.put(this.settings.source, this.dialogApplicationsTitle); this.settings.application = ""; this.settings.section = ""; this.settings.entry = ""; this.inputQuery = ""; this.inputExport = ""; this.inputImport = ""; this.importOriginalFileName = ""; // Daten aus fileUpload LinkedHashMap requestMultipart = new LinkedHashMap(); if (this.request != null) { ///////////////////////////////////////////////////////// String contentType = this.request.getHeader("Content-type"); if (contentType != null && contentType.startsWith("multipart/")) { // ob Import try { DiskFileUpload upload = new DiskFileUpload(); upload.setSizeMax(this.importMaxSize); upload.setSizeThreshold(0); // nicht im Memory sondern als // Datei speichern List items = upload.parseRequest(this.request); Iterator iter = items.iterator(); while (iter.hasNext()) { //FileItem item = (FileItem) iter.next(); DefaultFileItem item = (DefaultFileItem) iter.next(); if (item.isFormField()) { requestMultipart.put(item.getFieldName(), item.getString()); this.request.setAttribute(item.getFieldName(), item.getString()); } else { // aus upload if (item.getName() != null && !item.getName().equals("")) { //requestMultipart.put(item.getFieldName(),item.getStoreLocation()); requestMultipart.put(item.getFieldName(), item.getStoreLocation().getAbsolutePath()); this.request.setAttribute(item.getFieldName(), item.getStoreLocation().getAbsolutePath()); this.importOriginalFileName = item.getName(); } else { requestMultipart.put(item.getFieldName(), ""); this.request.setAttribute(item.getFieldName(), ""); }/*from w ww. ja va 2 s .c o m*/ } } } catch (FileUploadException e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); } } // MULTIPART Form ///////////////////////////////////////////////////////// if (this.getRequestValue("application") != null) { this.settings.application = this.getRequestValue("application"); } if (this.getRequestValue("section") != null) { this.settings.section = this.getRequestValue("section"); } if (this.getRequestValue("entry") != null) { this.settings.entry = this.getRequestValue("entry"); } if (this.getRequestValue("application_type") != null) { try { this.applicationType = Integer.parseInt(this.getRequestValue("application_type")); } catch (Exception e) { this.applicationType = 0; } } if (this.getRequestValue("section_type") != null) { try { this.sectionType = Integer.parseInt(this.getRequestValue("section_type")); } catch (Exception e) { this.sectionType = 0; } } if (this.getRequestValue("action") != null) { this.action = this.getRequestValue("action"); } if (this.getRequestValue("range") != null) { this.range = this.getRequestValue("range"); } if (this.getRequestValue("item") != null) { this.item = this.getRequestValue("item"); } if ((this.getRequestValue("btn_store.x") != null) && (this.getRequestValue("btn_store.y") != null)) { this.action = "store"; } else if ((this.getRequestValue("btn_insert.x") != null) && (this.getRequestValue("btn_insert.y") != null)) { this.action = "insert"; } else if ((this.getRequestValue("btn_delete.x") != null) && (this.getRequestValue("btn_delete.y") != null)) { this.action = "delete"; } else if ((this.getRequestValue("btn_schema.x") != null) && (this.getRequestValue("btn_schema.y") != null)) { this.action = "schema"; } else if ((this.getRequestValue("btn_duplicate.x") != null) && (this.getRequestValue("btn_duplicate.y") != null)) { this.action = "duplicate"; this.range = "entries"; } else if ((this.getRequestValue("btn_cancel.x") != null) && (this.getRequestValue("btn_cancel.y") != null)) { this.action = "show"; if (this.range.equals("application")) { this.range = "applications"; } else if (this.range.equals("section")) { this.range = "sections"; } else { this.range = this.range.equals("list") ? "sections" : "entries"; } } else if ((this.getRequestValue("btn_query.x") != null) && (this.getRequestValue("btn_query.y") != null)) { this.action = "query"; this.range = "entries"; if (this.getRequestValue("query_select_range") != null && this.getRequestValue("query_select_range").equals("2")) { this.item = "replace"; } } else if ((this.getRequestValue("btn_export.x") != null) && (this.getRequestValue("btn_export.y") != null)) { this.action = "export"; this.range = "entries"; } else if ((this.getRequestValue("btn_import.x") != null) && (this.getRequestValue("btn_import.y") != null)) { this.action = "import"; this.range = "entries"; } else if ((this.getRequestValue("btn_clipboard_copy.x") != null) && (this.getRequestValue("btn_clipboard_copy.y") != null)) { if (this.getRequestValue("last_action") != null) { this.action = this.getRequestValue("last_action"); } else { this.action = "show"; } this.clipboardAction = "copy"; } else if ((this.getRequestValue("btn_clipboard_paste.x") != null) && (this.getRequestValue("btn_clipboard_paste.y") != null)) { if (this.getRequestValue("last_action") != null) { this.action = this.getRequestValue("last_action"); } else { this.action = "show"; } this.clipboardAction = "paste"; } else if ((this.getRequestValue("btn_import_file.x") != null) && (this.getRequestValue("btn_import_file.y") != null)) { this.action = ((this.getRequestValue("last_action") != null) && this.getRequestValue("last_action").equals("new")) ? "insert" : "store"; this.range = "entry"; this.item = "upload"; } if (this.getRequestValue("input_query") != null) { this.inputQuery = this.getRequestValue("input_query"); } if (this.getRequestValue("input_query_replace") != null) { this.replaceQuery = this.getRequestValue("input_query_replace"); } if (this.getRequestValue("input_export") != null) { this.inputExport = this.getRequestValue("input_export"); } if (this.getRequestValue("export_documentation") != null) { this.exportDocumentation = 1; } if (this.getRequestValue("input_import") != null) { this.inputImport = this.getRequestValue("input_import"); } } if (this.applicationName.equals("")) { this.applicationName = this.settings.application; } if (this.enableShowDevelopmentData) { this.showDevelopmentData(requestMultipart); } }
From source file:specialdevice.fredck.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*from w w w.ja v a 2 s . c om*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=gb2312"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:specialdevice.fredck.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*from w ww . j av a 2s . c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) //System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); // fileName = StringUtil.getTmpStr() + "." + ext; File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } String fileUrl191 = fileUrl; out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl191 + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:thinwire.render.web.WebServlet.java
private void handleUserUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession httpSession = request.getSession(); ApplicationHolder holder = (ApplicationHolder) httpSession.getAttribute("instance"); if (holder.app != null) { try {/*w w w . j av a2s .c o m*/ DiskFileUpload upload = new DiskFileUpload(); upload.setSizeThreshold(1000000); upload.setSizeMax(-1); upload.setRepositoryPath("C:\\"); List<FileItem> items = upload.parseRequest(request); if (items.size() > 0) { FileChooser.FileInfo f = null; synchronized (holder.app.fileList) { for (FileItem fi : items) { if (!fi.isFormField()) { f = new FileChooser.FileInfo(fi.getName(), fi.getInputStream()); holder.app.fileList[0] = f; } } holder.app.fileList.notify(); } } } catch (FileUploadException e) { log.log(Level.SEVERE, null, e); } } response.sendRedirect("?_twr_=FileUploadPage.html"); }
From source file:tw.edu.chit.struts.action.portfolio.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*from w ww. jav a 2 s . c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); //out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }