List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
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.//w w w . j a v a 2s . 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(); }
From source file:edu.fullerton.ldvservlet.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//from w w w . ja v a2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("This action requires a multipart form with a file attached."); } ServletSupport servletSupport; servletSupport = new ServletSupport(); servletSupport.init(request, viewerConfig, false); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); ImageTable imageTable; String viewServletPath = request.getContextPath() + "/view"; try { imageTable = new ImageTable(servletSupport.getDb()); } catch (SQLException ex) { String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " " + ex.getLocalizedMessage(); throw new ServletException(ermsg); } try { HashMap<String, String> params = new HashMap<>(); ArrayList<Integer> uploadedIds = new ArrayList<>(); Page vpage = servletSupport.getVpage(); vpage.setTitle("Image upload"); try { servletSupport.addStandardHeader(version); servletSupport.addNavBar(); } catch (WebUtilException ex) { throw new ServerException("Adding nav bar after upload", ex); } // Parse the request List<FileItem> items = upload.parseRequest(request); int cnt = items.size(); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (!value.isEmpty()) { params.put(name, value); } } } for (FileItem item : items) { if (!item.isFormField()) { int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable); if (imgId != 0) { uploadedIds.add(imgId); } } } if (!uploadedIds.isEmpty()) { showImages(vpage, uploadedIds, imageTable, viewServletPath); } servletSupport.showPage(response); } catch (FileUploadException ex) { Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.krawler.esp.servlets.deskeramob_V1.java
public static String createProject(Connection conn, HttpServletRequest request, String companyid, String subdomain, String userid) throws ServiceException { String status = ""; DiskFileUpload fu = new DiskFileUpload(); java.util.List fileItems = null; PreparedStatement pstmt = null; String imageName = ""; try {/*ww w . j a v a 2s . c o m*/ fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("Admin.createProject", e); } java.util.HashMap arrParam = new java.util.HashMap(); java.util.Iterator k = null; for (k = fileItems.iterator(); k.hasNext();) { FileItem fi1 = (FileItem) k.next(); arrParam.put(fi1.getFieldName(), fi1.getString()); } try { pstmt = conn .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0"); pstmt.setString(1, companyid); ResultSet rs = pstmt.executeQuery(); int noProjects = 0; int maxProjects = 0; if (rs.next()) { noProjects = rs.getInt(1); } pstmt = conn.prepareStatement("select maxprojects from company where companyid =?"); pstmt.setString(1, companyid); rs = pstmt.executeQuery(); if (rs.next()) { maxProjects = rs.getInt(1); } if (noProjects == maxProjects) { return "The maximum limit for projects for this company has already reached"; } } catch (SQLException e) { throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e); } try { String projectid = UUID.randomUUID().toString(); String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString() .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim()); String nickName = AdminServlet.makeNickName(conn, projName, 1); if (StringUtil.isNullOrEmpty(projName)) { status = "failure"; } else { String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)"; pstmt = conn.prepareStatement(qry); pstmt.setString(1, projectid); pstmt.setString(2, projName); pstmt.setString(3, arrParam.get("aboutproject").toString()); pstmt.setString(4, imageName); pstmt.setString(5, companyid); pstmt.setString(6, nickName); int df = pstmt.executeUpdate(); if (df != 0) { pstmt = conn.prepareStatement( "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) " + "VALUES (?, ?, ?, ?, ?)"); pstmt.setString(1, projectid); pstmt.setString(2, userid); pstmt.setInt(3, 4); pstmt.setBoolean(4, true); pstmt.setInt(5, 0); pstmt.executeUpdate(); } // /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName}); if (arrParam.get("image").toString().length() != 0) { genericFileUpload uploader = new genericFileUpload(); uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath()); if (uploader.isUploaded()) { pstmt = null; // DbUtil.executeUpdate(conn, // "update project set image=? where projectid = ?", // new Object[] { // ProfileImageServlet.ImgBasePath + projectid // + uploader.getExt(), projectid }); pstmt = conn.prepareStatement("update project set image=? where projectid = ?"); pstmt.setString(1, ProfileImageServlet.ImgBasePath + projectid + "_200" + uploader.getExt()); pstmt.setString(2, projectid); pstmt.executeUpdate(); imageName = projectid + uploader.getExt(); } } com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain); status = "success"; AdminServlet.setDefaultWorkWeek(conn, projectid); conn.commit(); } } catch (ConfigurationException e) { status = "failure"; throw ServiceException.FAILURE("Admin.createProject", e); } catch (SQLException e) { status = "failure"; throw ServiceException.FAILURE("Admin.createProject", e); } return status; }
From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java
protected void showFormFieldParameter(FileItem item) { if (logger.isDebugEnabled()) { logger.debug("[param] {}={}", item.getFieldName(), item.getString()); }//from ww w. j a va 2s . co m }
From source file:com.manning.cmis.theblend.servlets.AddServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // we expected content -> return to add page dispatch("add.jsp", "Add something new. The Blend.", request, response); }//from ww w . j a va 2 s . c o m Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String parentId = null; String parentPath = null; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_PARENT_ID.equalsIgnoreCase(name)) { parentId = item.getString(); } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) { parentPath = item.getString(); } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) { properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString()); } } else { String name = item.getName(); if (name == null) { name = "file"; } else { // if the browser provided a path instead of a file name, // strip off the path int x = name.lastIndexOf('/'); if (x > -1) { name = name.substring(x + 1); } x = name.lastIndexOf('\\'); if (x > -1) { name = name.substring(x + 1); } name = name.trim(); if (name.length() == 0) { name = "file"; } } properties.put(PropertyIds.NAME, name); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!"); } try { // prepare the content stream ContentStream contentStream = null; try { String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // find the parent folder // (we don't deal with unfiled documents here) Folder parent = null; if (parentId != null) { parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } else { parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } // create the document try { newId = session.createDocument(properties, parent, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:ea.ejb.AbstractFacade.java
public Map<String, String> obtenerDatosFormConImagen(HttpServletRequest request) { Map<String, String> mapDatos = new HashMap(); final String SAVE_DIR = "uploadImages"; // Parametros del form String description = null;/*from w w w. j a v a 2 s . c om*/ String url_image = null; String id_grupo = null; boolean isMultiPart; String filePath; int maxFileSize = 50 * 1024; int maxMemSize = 4 * 1024; File file = null; InputStream inputStream = null; OutputStream outputStream = null; // gets absolute path of the web application String appPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file filePath = appPath + File.separator + "assets" + File.separator + "img" + File.separator + SAVE_DIR; String filePathWeb = "assets/img/" + SAVE_DIR + "/"; // creates the save directory if it does not exists File fileSaveDir = new File(filePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } // Check that we have a file upload request isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { // Parse the request List<FileItem> items = getMultipartItems(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); int offset = 0; int leidos = 0; while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { // ProcessFormField String name = item.getFieldName(); String value = item.getString(); if (name.equals("description_post_grupo") || name.equals("descripcion")) { description = value; } else if (name.equals("id_grupo")) { id_grupo = value; } } else { // ProcessUploadedFile try { String itemName = item.getName(); if (!itemName.equals("")) { url_image = filePathWeb + item.getName(); // read this file into InputStream inputStream = item.getInputStream(); // write the inputStream to a FileOutputStream if (file == null) { String fileDirUpload = filePath + File.separator + item.getName(); file = new File(fileDirUpload); // crea el archivo en el sistema file.createNewFile(); if (file.exists()) { outputStream = new FileOutputStream(file); } } int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, offset, read); leidos += read; } offset += leidos; leidos = 0; System.out.println("Done!"); } else { url_image = ""; } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } if (outputStream != null) { try { // outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } mapDatos.put("descripcion", description); mapDatos.put("imagen", url_image); mapDatos.put("id_grupo", id_grupo); return mapDatos; }
From source file:net.sf.ginp.GinpServlet.java
/** * Extract Command Parameter NAmes and Values from the HTTP Request. * *@param req HTTP Request./*w w w. java2s .c o m*/ *@return A vector of Command Parameters. */ final Vector extractParameters(final HttpServletRequest req) { Vector params = new Vector(); Enumeration names = req.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); params.add(new CommandParameter(name, req.getParameter(name))); log.debug("new CommandParameter(" + name + ", " + req.getParameter(name) + ")"); } ServletRequestContext reqContext = new ServletRequestContext(req); if (FileUpload.isMultipartContent(reqContext)) { try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Set upload parameters //upload.setSizeThreshold(yourMaxMemorySize); //upload.setSizeMax(yourMaxRequestSize); //upload.setRepositoryPath(yourTempDirectory); // Parse the request List items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.add(new CommandParameter(item.getFieldName(), item.getString())); } else { CommandParameter fileParam = new CommandParameter(item.getFieldName(), item.getName()); fileParam.setObject(item.getInputStream()); params.add(fileParam); } } } catch (Exception ex) { log.error("extract parameters error getting input stream" + " from file upload", ex); } } return params; }
From source file:com.scooterframework.web.controller.ScooterRequestFilter.java
protected String requestInfo(boolean skipStatic, HttpServletRequest request) { String method = getRequestMethod(request); String requestPath = getRequestPath(request); String requestPathKey = RequestInfo.generateRequestKey(requestPath, method); String s = requestPathKey;//from ww w .j a va 2s . c o m String queryString = request.getQueryString(); if (queryString != null) s += "?" + queryString; CurrentThreadCacheClient.cacheHttpMethod(method); CurrentThreadCacheClient.cacheRequestPath(requestPath); CurrentThreadCacheClient.cacheRequestPathKey(requestPathKey); if (skipStatic) return s; //request header Properties headers = new Properties(); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); if (value != null) headers.setProperty(name, value); } CurrentThreadCache.set(Constants.REQUEST_HEADER, headers); if (isLocalRequest(request)) { CurrentThreadCache.set(Constants.LOCAL_REQUEST, Constants.VALUE_FOR_LOCAL_REQUEST); } if (isFileUploadRequest(request)) { CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST, Constants.VALUE_FOR_FILE_UPLOAD_REQUEST); try { List<FileItem> files = new ArrayList<FileItem>(); ServletFileUpload fileUpload = EnvConfig.getInstance().getServletFileUpload(); List<?> items = fileUpload.parseRequest(request); for (Object fi : items) { FileItem item = (FileItem) fi; if (item.isFormField()) { ActionControl.storeToRequest(item.getFieldName(), item.getString()); } else if (!item.isFormField() && !"".equals(item.getName())) { files.add(item); } } CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST_FILES, files); } catch (Exception ex) { CurrentThreadCacheClient.storeError(new FileUploadException(ex)); } } return s; }
From source file:cn.itcast.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 ww w . jav a 2s.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 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:com.vectorcast.plugins.vectorcastexecution.job.NewMultiJobTest.java
public void basicCommon(String projectFile) throws Exception { StaplerRequest request = Mockito.mock(StaplerRequest.class); StaplerResponse response = Mockito.mock(StaplerResponse.class); JSONObject jsonForm = new JSONObject(); jsonForm.put("manageProjectName", "/home/jenkins/vcast/project.vcm"); jsonForm.put("optionClean", true); when(request.getSubmittedForm()).thenReturn(jsonForm); FileItem fileItem = Mockito.mock(FileItem.class); when(request.getFileItem("manageProject")).thenReturn(fileItem); when(fileItem.getString()).thenReturn(projectFile); NewMultiJob job = new NewMultiJob(request, response, false); Assert.assertEquals("project", job.getBaseName()); job.create(false);//from ww w. j av a 2 s.c o m Assert.assertTrue(job.getTopProject() != null); Assert.assertEquals(project, job.getTopProject()); // Check build wrappers - main project... Assert.assertEquals(1, bldWrappersList.size()); BuildWrapper wrapper = bldWrappersList.get(0); Assert.assertTrue(wrapper instanceof PreBuildCleanup); PreBuildCleanup cleanup = (PreBuildCleanup) wrapper; Assert.assertTrue(cleanup.getDeleteDirs()); // Check build actions - main project... Assert.assertEquals(5, bldrsList.size()); Assert.assertTrue(bldrsList.get(0) instanceof VectorCASTSetup); Assert.assertTrue(bldrsList.get(1) instanceof MultiJobBuilder); Assert.assertTrue(bldrsList.get(2) instanceof CopyArtifact); Assert.assertTrue(bldrsList.get(3) instanceof CopyArtifact); Assert.assertTrue(bldrsList.get(4) instanceof VectorCASTCommand); // Check publishers - main project... checkPublishers(publisherList); // Now check the additional build/report projects // Build/execute - project 1 checkBuildExecuteSteps3(bldrsList1); checkPublishers(publisherList1); // Build/execute - project 2 checkBuildExecuteSteps3(bldrsList2); checkPublishers(publisherList2); }