List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.ephesoft.dcma.gwt.admin.bm.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, DeploymentService deploymentService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;// ww w. ja v a 2 s . c o m InputStream instream = null; OutputStream out = null; String zipWorkFlowName = BatchClassManagementConstants.EMPTY_STRING, tempOutputUnZipDir = BatchClassManagementConstants.EMPTY_STRING, systemFolderPath = BatchClassManagementConstants.EMPTY_STRING; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = BatchClassManagementConstants.EMPTY_STRING; String zipPathname = BatchClassManagementConstants.EMPTY_STRING; List<FileItem> items; try { items = (List<FileItem>) upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField() && "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE]; int len = instream.read(buf); while ((len) > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { LOG.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(instream); } } } } catch (FileUploadException e) { LOG.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { LOG.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); systemFolderPath = importBatchClass.getSystemFolder(); if (systemFolderPath == null) { systemFolderPath = BatchClassManagementConstants.EMPTY_STRING; } } catch (Exception e) { tempZipFile.delete(); LOG.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { IOUtils.closeQuietly(serializableFileStream); } } else { LOG.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriterMethod(printWriter, zipWorkFlowName, tempOutputUnZipDir, systemFolderPath, uncList, isWorkflowDeployed, isWorkflowEqual); }
From source file:com.insurance.manage.UploadFile.java
private void uploadFire(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;// ww w . ja v a 2 s.com String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("fire") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/fire/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "firepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:com.insurance.manage.UploadFile.java
private void uploadLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;// ww w. j av a 2s . c om String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("life") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/life/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "lifepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:dk.clarin.tools.rest.register.java
public String getarg(HttpServletRequest request, List<FileItem> items, String name) { /*//from w w w .j av a 2 s. c om * 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:com.silverpeas.form.displayers.AbstractFileFieldDisplayer.java
protected String processUploadedFile(List<FileItem> items, String parameterName, PagesContext pagesContext) throws IOException { String attachmentId = null;//w ww .j a v a 2 s .c o m FileItem item = FileUploadUtil.getFile(items, parameterName); if (item != null && !item.isFormField()) { String componentId = pagesContext.getComponentId(); String userId = pagesContext.getUserId(); String objectId = pagesContext.getObjectId(); if (StringUtil.isDefined(item.getName())) { String fileName = FileUtil.getFilename(item.getName()); long size = item.getSize(); if (size > 0L) { SimpleDocument document = createSimpleDocument(objectId, componentId, item, fileName, userId, false); attachmentId = document.getId(); } } } return attachmentId; }
From source file:dk.clarin.tools.rest.register.java
public String getargs(HttpServletRequest request, List<FileItem> items) { String arg = ""; /*//from ww w . j a v a 2 s.com * Parse the request */ @SuppressWarnings("unchecked") Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames(); 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()) { arg = arg + " (" + workflow.quote(item.getFieldName()) + "." + workflow.quote(item.getString("UTF-8").trim()) + ")"; } } } catch (Exception ex) { logger.error("uploadHandler.parseRequest Exception"); } } for (Enumeration<String> e = parmNames; e.hasMoreElements();) { String parmName = e.nextElement(); arg = arg + " (" + workflow.quote(parmName) + "."; String vals[] = request.getParameterValues(parmName); for (int j = 0; j < vals.length; ++j) { arg += " " + workflow.quote(vals[j]) + ""; } arg += ")"; } logger.debug("arg = [" + arg + "]"); return arg; }
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /*from w ww.j a v a2s.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:it.geosolutions.geofence.gui.server.UploadServlet.java
@SuppressWarnings("unchecked") @Override/* www .ja va2s.c o m*/ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); File uploadedFile = null; // Parse the request try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) { continue; } String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } uploadedFile = File.createTempFile(fileName, ""); // if (uploadedFile.createNewFile()) { item.write(uploadedFile); resp.setStatus(HttpServletResponse.SC_CREATED); resp.flushBuffer(); // uploadedFile.delete(); // } else // throw new IOException( // "The file already exists in repository."); } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while creating the file : " + e.getMessage()); } try { String wkt = calculateWKT(uploadedFile); resp.getWriter().print(wkt); } catch (Exception exc) { resp.getWriter().print("Error : " + exc.getMessage()); logger.error("ERROR ********** " + exc); } uploadedFile.delete(); } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:ManageViewerFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j a v a 2 s.co m*/ * * @param request servlet request * @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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //get the viewer files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String viewerid = request.getParameter("viewerid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getViewerFiles")) { //getting viewer files //first get the filenames in the directory. //I will get the list of files in this directory and send it String studyPath = getServletContext().getRealPath("/viewer/" + viewerid); File root = new File(studyPath); File[] list = root.listFiles(); ArrayList<String> fileItemList = new ArrayList<String>(); if (list == null) { System.out.println("List is null"); return; } for (File f : list) { if (f.isDirectory()) { ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName()); for (int i = 0; i < dirItems.size(); i++) { fileItemList.add(dirItems.get(i)); } } else { //System.out.println(f.getName()); fileItemList.add(f.getName()); } } System.out.println("**** Printing the fileItems now **** "); String outputStr = ""; for (int i = 0; i < fileItemList.size(); i++) { outputStr += fileItemList.get(i) + "::::"; } out.println(outputStr); } else if (command.equalsIgnoreCase("addViewerFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/viewer/" + viewerid); File studyFolder = new File(studyFolderPath); //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); int cnt = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { // cnt++; String name = new File(item.getName()).getName(); //write the file to disk if (!studyFolder.exists()) { studyFolder.mkdir(); System.out.println("The Folder has been created"); } item.write(new File(studyFolder + File.separator + name)); System.out.println("File name is :: " + name); } } out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteViewerFiles")) { //get the array of files and delete thems String[] mpk; //get the array of file-names mpk = request.getParameterValues("fileNames"); for (int i = 0; i < mpk.length; i++) { String filePath = getServletContext().getRealPath("/viewer/" + viewerid + "/" + mpk[i]); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:controller.uploadImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . j av a 2 s. c om * * @param request servlet request * @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, Exception { response.setContentType("text/html;charset=UTF-8"); //ArrayList<String> ls=new ArrayList(); try (PrintWriter out = response.getWriter()) { //if (!ServletFileUpload.isMultipartContent(request)) { //if not, we stop here //PrintWriter writer = response.getWriter(); //writer.println("Error: Form must has enctype=multipart/form-data."); //writer.flush(); //return; //} // configures upload settings HttpSession ssn = request.getSession(); DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk if (storeFile.exists()) { ssn.setAttribute("uploadMsg", "File exists"); response.sendRedirect("register.htm?name=index"); } else { //if(item.isInMemory()) item.write(storeFile); ssn.setAttribute("imgname", storeFile.getName()); ssn.setAttribute("uploadMsg", "File uploded"); response.sendRedirect("register.htm?name=null"); } } else { ssn.setAttribute(item.getFieldName(), item.getString()); } } } } catch (Exception ex) { ssn.setAttribute("uploadMsg", ex.getMessage()); response.sendRedirect("register.htm?name=index"); } } }