List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /*from w ww. j a v a 2 s . c om*/ * 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:it.swim.servlet.profilo.azioni.RilasciaFeedBackServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//from w w w. ja va 2 s. co m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi // ad una classe di utilita' String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request); List<FileItem> items; int punteggioFeedBack = 0; String commento = ""; // se e' null e' perche' l'utente non e' collegato e allora devo fare il // redirect alla home if (emailUtenteCollegato == null) { response.sendRedirect("../../home"); return; } try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). // ... (do your job here) if (item.getFieldName().equals("punteggioFeedBack")) { punteggioFeedBack = Integer.parseInt(item.getString().trim()); } if (item.getFieldName().equals("commentoFeedBack")) { commento = item.getString().trim(); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (punteggioFeedBack < 1 || punteggioFeedBack > 5) { request.setAttribute("erroreNelPunteggio", "Il punteggio deve essere compreso tra 1 e 5"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); return; } if (commento.isEmpty()) { commento = "Non ci sono commenti rilasciati"; } try { collab.rilasciaFeedback(idCollaborazione, punteggioFeedBack, commento); } catch (LoginException e) { // TODO Auto-generated catch block request.setAttribute("erroreNelPunteggio", "Collaborazione a cui aggiungere il feedBack non trovata"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); return; } request.setAttribute("feedBackRilasciato", "Feedback rilasciato con successo"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); }
From source file:com.silverpeas.importExportPeas.servlets.ImportDragAndDrop.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("importExportPeas", "ImportDragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); HttpRequest request = HttpRequest.decorate(req); request.setCharacterEncoding("UTF-8"); if (!request.isContentInMultipart()) { res.getOutputStream().println("SUCCESS"); return;//from w w w . ja v a 2s . c o m } String userLanguage = null; StringBuilder result = new StringBuilder(); try { String componentId = request.getParameter("ComponentId"); String topicId = request.getParameter("TopicId"); if (!StringUtil.isDefined(topicId)) { String sessionId = request.getParameter("SessionId"); SessionManagementFactory factory = SessionManagementFactory.getFactory(); SessionManagement sessionManagement = factory.getSessionManagement(); SessionInfo session = sessionManagement.getSessionInfo(sessionId); topicId = session.getAttribute("Silverpeas_DragAndDrop_TopicId"); } String userId = request.getParameter("UserId"); userLanguage = StringUtil.isNotDefined(userId) ? I18NHelper.defaultLanguage : UserDetail.getById(userId).getUserPreferences().getLanguage(); boolean ignoreFolders = StringUtil.getBooleanValue(request.getParameter("IgnoreFolders")); boolean draftUsed = StringUtil.getBooleanValue(request.getParameter("Draft")); SilverTrace.info("importExportPeas", "Drop", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId + " topicId = " + topicId + " userId = " + userId + " ignoreFolders = " + ignoreFolders + ", draftUsed = " + draftUsed); String savePath = FileRepositoryManager.getTemporaryPath() + "tmpupload" + File.separator + topicId + System.currentTimeMillis() + File.separator; List<FileItem> items = request.getFileItems(); for (FileItem item : items) { if (!item.isFormField()) { String fileUploadId = item.getFieldName().substring(4); String parentPath = FileUploadUtil.getParameter(items, "relpathinfo" + fileUploadId, null); String fileName = FileUploadUtil.getFileName(item); if (StringUtil.isDefined(parentPath)) { if (parentPath.endsWith(":\\")) { // special case for file on root of disk parentPath = parentPath.substring(0, parentPath.indexOf(':') + 1); } } parentPath = FileUtil.convertPathToServerOS(parentPath); SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "fileName = " + fileName); if (fileName != null) { if (fileName.contains(File.separator)) { fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)); parentPath = parentPath + File.separatorChar + fileName.substring(0, fileName.lastIndexOf(File.separatorChar)); } SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + fileName); } if (!ignoreFolders) { if (parentPath != null && parentPath.length() > 0) { result.append("newFolder=true&"); fileName = File.separatorChar + parentPath + File.separatorChar + fileName; } } if (!"".equals(savePath)) { File f = new File(savePath + fileName); File parent = f.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } item.write(f); } } else { SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getFieldName() + " - " + item.getString()); } } MassiveReport massiveReport = new MassiveReport(); UserDetail userDetail = OrganisationControllerFactory.getOrganisationController().getUserDetail(userId); try { MassiveDocumentImport massiveImporter = new MassiveDocumentImport(); ImportSettings settings = new ImportSettings(savePath, userDetail, componentId, topicId, draftUsed, true, ImportSettings.FROM_DRAGNDROP); ImportReport importReport = massiveImporter.importDocuments(settings, massiveReport); if (isDefaultClassificationModifiable(topicId, componentId)) { ComponentReport componentReport = importReport.getListComponentReport().get(0); List<MassiveReport> listMassiveReport = componentReport.getListMassiveReports(); for (MassiveReport theMassiveReport : listMassiveReport) { List<UnitReport> listMassiveUnitReport = theMassiveReport.getListUnitReports(); for (UnitReport unitReport : listMassiveUnitReport) { if (unitReport.getStatus() == UnitReport.STATUS_PUBLICATION_CREATED) { result.append("pubid=").append(unitReport.getLabel()).append("&"); } } } } } catch (ImportExportException ex) { massiveReport.setError(UnitReport.ERROR_NOT_EXISTS_OR_INACCESSIBLE_DIRECTORY); SilverpeasTransverseErrorUtil.throwTransverseErrorIfAny(ex, userLanguage); res.getOutputStream().println("ERROR"); return; } } catch (Exception e) { SilverTrace.debug("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", e); final StringBuilder sb = new StringBuilder("ERROR: "); String transverseMessage = SilverpeasTransverseWebErrorUtil.performAppletAlertExceptionMessage(e, userLanguage); if (isDefined(transverseMessage)) { sb.append(transverseMessage); } else { sb.append(e.getMessage()); } res.getOutputStream().println(sb.toString()); return; } if (result.length() > 0) { res.getOutputStream().println(result.substring(0, result.length() - 1)); } else { res.getOutputStream().println("SUCCESS"); } }
From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java
/** * Process the uploaded file// ww w.j a va 2 s.c o m * * @param item The multipart form file data. * * @return The uploaded file as File object. * * @throws Exception */ private File processUploadedFile(FileItem item) throws Exception { File eml = null; // Process a file upload if (!item.isFormField()) { // Get object information String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String tmpdir = System.getProperty("java.io.tmpdir"); logger.debug("FILE: " + tmpdir + "/" + fileName); eml = new File(tmpdir + "/" + fileName); item.write(eml); } return eml; }
From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java
@SuppressWarnings("unchecked") protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("service({}, {})", request, response); boolean isMultipart = ServletFileUpload.isMultipartContent(request); InputStream is = null;//from www.j a v a 2 s . c o m String id = ""; if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Parse the request and get all parameters and the uploaded file List<FileItem> items; try { items = upload.parseRequest(request); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { // if (item.getFieldName().equals("format")) { format = // item.getString("UTF-8"); } if (item.getFieldName().equals("id")) { id = item.getString("UTF-8"); } // if (item.getFieldName().equals("filename")) { // filename = item.getString("UTF-8"); } } else { is = item.getInputStream(); } } // Retrieve token ZohoToken zot = ZohoTokenDAO.findByPk(id); // Save document if (Config.REPOSITORY_NATIVE) { String sysToken = DbSessionManager.getInstance().getSystemToken(); String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode()); new DbDocumentModule().checkout(sysToken, path, zot.getUser()); new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser()); } else { String sysToken = JcrSessionManager.getInstance().getSystemToken(); String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode()); new JcrDocumentModule().checkout(sysToken, path, zot.getUser()); new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser()); } } catch (FileUploadException e) { log.error(e.getMessage(), e); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); } catch (DatabaseException e) { log.error(e.getMessage(), e); } catch (FileSizeExceededException e) { log.error(e.getMessage(), e); } catch (UserQuotaExceededException e) { log.error(e.getMessage(), e); } catch (VirusDetectedException e) { log.error(e.getMessage(), e); } catch (VersionException e) { log.error(e.getMessage(), e); } catch (LockException e) { log.error(e.getMessage(), e); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); } catch (ExtensionException e) { log.error(e.getMessage(), e); } catch (AutomationException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } } }
From source file:com.silverpeas.attachment.servlets.DragAndDrop.java
/** * Method declaration/*from w w w. j a va2 s.co m*/ * @param req * @param res * @throws IOException * @throws ServletException * @see */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); if (!FileUploadUtil.isRequestMultipart(req)) { res.getOutputStream().println("SUCCESS"); return; } ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false); try { req.setCharacterEncoding("UTF-8"); String componentId = req.getParameter("ComponentId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId); String id = req.getParameter("PubId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id); String userId = req.getParameter("UserId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId); String context = req.getParameter("Context"); boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt")); List<FileItem> items = FileUploadUtil.parseRequest(req); for (FileItem item : items) { SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getFieldName()); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getName() + "; " + item.getString("UTF-8")); if (!item.isFormField()) { String fileName = item.getName(); if (fileName != null) { String physicalName = saveFileOnDisk(item, componentId, context); String mimeType = AttachmentController.getMimeType(fileName); long size = item.getSize(); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item size = " + size); // create AttachmentDetail Object AttachmentDetail attachment = new AttachmentDetail( new AttachmentPK(null, "useless", componentId), physicalName, fileName, null, mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId)); attachment.setAuthor(userId); try { AttachmentController.createAttachment(attachment, bIndexIt); } catch (Exception e) { // storing data into DB failed, delete file just added on disk deleteFileOnDisk(physicalName, componentId, context); throw e; } // Specific case: 3d file to convert by Actify Publisher if (actifyPublisherEnable) { String extensions = settings.getString("Actify3dFiles"); StringTokenizer tokenizer = new StringTokenizer(extensions, ","); // 3d native file ? boolean fileForActify = false; SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "nb tokenizer =" + tokenizer.countTokens()); String type = FileRepositoryManager.getFileExtension(fileName); while (tokenizer.hasMoreTokens() && !fileForActify) { String extension = tokenizer.nextToken(); fileForActify = type.equalsIgnoreCase(extension); } if (fileForActify) { String dirDestName = "a_" + componentId + "_" + id; String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separatorChar + dirDestName; String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath; if (!new File(destPath).exists()) { FileRepositoryManager.createGlobalTempPath(actifyWorkingPath); } String normalizedFileName = FilenameUtils.normalize(fileName); if (normalizedFileName == null) { normalizedFileName = FilenameUtils.getName(fileName); } String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath + File.separatorChar + normalizedFileName; FileRepositoryManager .copyFile(AttachmentController.createPath(componentId, "Images") + File.separatorChar + physicalName, destFile); } } } } } } catch (Exception e) { SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }
From source file:dk.clarin.tools.rest.register.java
public String getarg(HttpServletRequest request, List<FileItem> items, String name) { /*//from ww w. j a v a 2s. com * Parse the request */ @SuppressWarnings("unchecked") boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request); logger.debug("is_multipart_formData:" + (is_multipart_formData ? "ja" : "nej")); if (is_multipart_formData) { try { Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { if (name.equals(item.getFieldName())) return item.getString("UTF-8").trim(); } } } catch (Exception ex) { logger.error("uploadHandler.parseRequest Exception"); } } Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames(); for (Enumeration<String> e = parmNames; e.hasMoreElements();) { String parmName = e.nextElement(); String vals[] = request.getParameterValues(parmName); for (int j = 0; j < vals.length; ++j) { if (name.equals(parmName)) { logger.debug("parmName:" + parmName + " equals:" + name + " , return " + vals[j]); return vals[j]; } } } return null; }
From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java
protected void workingdoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/plain"); out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>"); out.println();// ww w .java2 s .com DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /* * Set the size threshold, above which content will be stored on disk. */ fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB /* * Set the temporary directory to store the uploaded files of size above * threshold. */ fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { /* * Parse the request */ List<FileItem> items = uploadHandler.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString()); } else { // Handle Uploaded files. out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); /* * Write file to the ultimate location. */ File file = new File(destinationDir, "LogisticNetwork.mxe"); item.write(file); } out.close(); } } catch (FileUploadException ex) { log("Error encountered while parsing the request", ex); } catch (Exception ex) { log("Error encountered while uploading file", ex); } }
From source file:com.app.framework.web.MultipartFilter.java
/** * Process multipart request item as file field. The name and FileItem * object of each file field will be added as attribute of the given * HttpServletRequest. If a FileUploadException has occurred when the file * size has exceeded the maximum file size, then the FileUploadException * will be added as attribute value instead of the FileItem object. * * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. *//* ww w.j a v a 2s . com*/ private void processFileField(FileItem fileField, HttpServletRequest request) { if (fileField.getName().length() <= 0) { // No file uploaded. request.setAttribute(fileField.getFieldName(), null); } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) { // File size exceeds maximum file size. request.setAttribute(fileField.getFieldName(), new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk space. fileField.delete(); } else { // File uploaded with good size. request.setAttribute(fileField.getFieldName(), fileField); } }
From source file:com.slamd.admin.RequestInfo.java
/** * Creates a new set of request state information using the provided request * and response./*w w w . ja v a 2s . c om*/ * * @param request Information about the HTTP request issued by the client. * @param response Information about the HTTP response that will be returned * to the client. */ public RequestInfo(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; generateHTML = true; debugInfo = new StringBuilder(); htmlBody = new StringBuilder(); infoMessage = new StringBuilder(); if (request != null) { servletBaseURI = request.getRequestURI(); userIdentifier = request.getRemoteUser(); if (FileUpload.isMultipartContent(request)) { try { FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory()); multipartFieldList = fileUpload.parseRequest(request); Iterator iterator = multipartFieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String name = fileItem.getFieldName(); if (name.equals(Constants.SERVLET_PARAM_SECTION)) { section = new String(fileItem.get()); } else if (name.equals(Constants.SERVLET_PARAM_SUBSECTION)) { subsection = new String(fileItem.get()); } } } catch (FileUploadException fue) { fue.printStackTrace(); } } else { section = request.getParameter(Constants.SERVLET_PARAM_SECTION); subsection = request.getParameter(Constants.SERVLET_PARAM_SUBSECTION); } } if (section == null) { section = ""; } if (subsection == null) { subsection = ""; } }