List of usage examples for org.apache.commons.fileupload DiskFileUpload parseRequest
public List parseRequest(HttpServletRequest req) throws FileUploadException
From source file:com.rapidsist.portal.cliente.editor.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./* ww w . j av a2 s.c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("PASO POR EL METODO doPost DEL SERVLET SimpleUploaderServlet"); 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; 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); 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 = ""; } } catch (Exception ex) { retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * //from w w w . jav a 2 s . c o m * 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. * */ 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); 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"; } System.out.println("111111222111111111"); out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.corejsf.UploadFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //System.out.println("**** doFilter #1"); if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return;// ww w. ja v a 2 s. co m } //System.out.println("**** doFilter #2"); HttpServletRequest httpRequest = (HttpServletRequest) request; boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest); if (!isMultipartContent) { chain.doFilter(request, response); return; } //System.out.println("**** doFilter #3"); DiskFileUpload upload = new DiskFileUpload(); if (repositoryPath != null) upload.setRepositoryPath(repositoryPath); try { List list = upload.parseRequest(httpRequest); final Map map = new HashMap(); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); //System.out.println("form filed="+item.getFieldName()+" : "+str); if (item.isFormField()) { String str = item.getString("UTF-8"); map.put(item.getFieldName(), new String[] { str }); } else { httpRequest.setAttribute(item.getFieldName(), item); } } chain.doFilter(new HttpServletRequestWrapper(httpRequest) { public Map getParameterMap() { return map; } // busywork follows ... should have been part of the wrapper public String[] getParameterValues(String name) { Map map = getParameterMap(); return (String[]) map.get(name); } public String getParameter(String name) { String[] params = getParameterValues(name); if (params == null) return null; return params[0]; } public Enumeration getParameterNames() { Map map = getParameterMap(); return Collections.enumeration(map.keySet()); } }, response); } catch (FileUploadException ex) { log.error(ex.getMessage()); ServletException servletEx = new ServletException(); servletEx.initCause(ex); throw servletEx; } }
From source file:com.mockey.ui.UploadConfigurationServlet.java
/** * //w ww .ja v a2 s .c o m * * @param req * basic request * @param resp * basic resp * @throws ServletException * basic * @throws IOException * basic */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = null; String definitionsAsString = null; String taglistValue = ""; // *********************************** // STEP #1 - READ DATA // *********************************** if (req.getParameter("viaUrl") != null) { url = req.getParameter("url"); taglistValue = req.getParameter("taglist"); try { InputStream fstream = new URL(url).openStream(); if (fstream != null) { BufferedReader br = new BufferedReader( new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8))); StringBuffer inputString = new StringBuffer(); // Read File Line By Line String strLine = null; // READ FIRST while ((strLine = br.readLine()) != null) { // Print the content on the console inputString.append(new String(strLine.getBytes(HTTP.UTF_8))); } definitionsAsString = inputString.toString(); } } catch (Exception e) { logger.error("Unable to reach url: " + url, e); Util.saveErrorMessage("Unable to reach url: " + url, req); } } else { byte[] data = null; try { // STEP 1. GATHER UPLOADED ITEMS // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Parse the request List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { data = item.get(); } else { String name = item.getFieldName(); if ("taglist".equals(name)) { taglistValue = item.getString(); } } } if (data != null && data.length > 0) { definitionsAsString = new String(data); } } catch (Exception e) { logger.error("Unable to read or parse file: ", e); Util.saveErrorMessage("Unable to upload or parse file.", req); } } // *********************************** // STEP #2 - PERSIST DATA // *********************************** try { if (definitionsAsString != null) { MockeyXmlFileManager configurationReader = new MockeyXmlFileManager(); ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString, taglistValue); Util.saveSuccessMessage("Service definitions uploaded.", req); req.setAttribute("conflicts", results.getConflictMsgs()); req.setAttribute("additions", results.getAdditionMessages()); } else { Util.saveErrorMessage("Unable to upload or parse empty file.", req); } } catch (Exception e) { Util.saveErrorMessage("Unable to upload or parse file.", req); } RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp"); dispatch.forward(req, resp); }
From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.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 ava 2 s . co 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(); // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (fileSize < 30240) { String typeStr = request.getParameter("Type"); String currentPath = ""; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); 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 = FckeditorUtil.getNameWithoutExtension(fileName); String ext = FckeditorUtil.getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, 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); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } 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"; } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:cn.itcast.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 a va2s.com*/ * */ @Override 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); 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"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:ca.myewb.frame.PostParamWrapper.java
public PostParamWrapper(HttpServletRequest request) throws Exception { if (!FileUpload.isMultipartContent(request)) { return;// w w w . jav a 2s . co m } DiskFileUpload upload = new DiskFileUpload(); upload.setRepositoryPath(Helpers.getUserFilesDir() + "/temp"); try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { stringParams.put(item.getFieldName(), item.getString()); allParams.put(item.getFieldName(), item); } else if (item.getSize() > 0) { fileParams.put(item.getFieldName(), item); allParams.put(item.getFieldName(), item); } } } catch (FileUploadException ex) { log.debug("The file upload exception returned the message: " + ex.getMessage()); // Usually means user cancelled upload and connection timed out. // Do nothing. } }
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * //from w w w .j av a2 s. com * 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. * */ 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); File pathToSave = new File(currentDirPath, fileName); if (extIsAllowed(typeStr, ext)) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS"); newName = format.format(new Date()) + String.valueOf(((int) (Math.random() * 100000))) + "." + ext; fileUrl = currentPath + "/" + newName; pathToSave = new File(currentDirPath, newName); 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"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.krawler.esp.servlets.importProjectPlanCSV.java
public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException { String result = ""; try {// w w w. j a va 2 s. com String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importplans"; org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload(); org.apache.commons.fileupload.FileItem fi = null; org.apache.commons.fileupload.FileItem docTmpFI = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } long size = 0; String Ext = ""; String fileName = null; boolean fileupload = false; java.io.File destDir = new java.io.File(destinationDirectory); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); java.util.HashMap arrParam = new java.util.HashMap(); for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) { fi = (org.apache.commons.fileupload.FileItem) k.next(); arrParam.put(fi.getFieldName(), fi.getString()); if (!fi.isFormField()) { size = fi.getSize(); fileName = new String(fi.getName().getBytes(), "UTF8"); docTmpFI = fi; fileupload = true; } } if (fileupload) { if (!destDir.exists()) { destDir.mkdirs(); } if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (size != 0) { File uploadFile = new File(destinationDirectory + "/" + fileid + Ext); docTmpFI.write(uploadFile); // fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size); result = fileid + Ext; } } } catch (ConfigurationException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } catch (Exception ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } return result; }
From source file:com.rapidsist.portal.cliente.editor.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 www .ja va 2 s . c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("PASO POR EL METODO doPost DEL SERVLET ConnectorServlet"); 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); 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(); }