List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:controller.insertProduct.java
private void insertProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String productType = null;/*from ww w . jav a 2s. co m*/ String resolution = null; String hdmi = null; String usb = null; String model = null; String size = null; String warranty = null; String productName = null; int price = 0; String description = null; Integer quantity = null; String produceID = null; String image = null; String uploadDirectory = "/Product/Images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); File uploadDir; File storeFile; try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadDirectory + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); image = produceID + "/" + fileName; System.out.println(storeFile.getPath()); } else { switch (item.getFieldName()) { case "productName": productName = item.getString("UTF-8"); break; case "produceID": { produceID = item.getString("UTF-8"); uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID); if (!uploadDir.exists()) { uploadDir.mkdir(); } uploadDirectory = uploadPath + uploadDirectory + "/" + produceID; break; } case "price": price = (Integer.parseInt(item.getString("UTF-8"))); break; case "quantity": quantity = (Integer.parseInt(item.getString("UTF-8"))); break; case "productType": productType = item.getString("UTF-8"); break; case "resolution": resolution = item.getString("UTF-8"); break; case "hdmi": hdmi = item.getString("UTF-8"); break; case "usb": usb = item.getString("UTF-8"); break; case "Model": model = item.getString("UTF-8"); break; case "size": size = item.getString("UTF-8"); break; case "warranty": warranty = item.getString("UTF-8"); break; case "description": { description = item.getString("UTF-8"); System.out.println(description); break; } } } } } } catch (Exception ex) { System.out.println(ex); } @SuppressWarnings("null") ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty); Products product = new Products(productName, price, description, quantity, image, prinfo, produceID); if (ProductsDAO.insertProduct(product)) { out.print( "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } else { out.print( "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } }
From source file:mercury.Controller.java
public void putAllRequestParametersInAttributes(HttpServletRequest request) { ArrayList fileBeanList = new ArrayList(); HashMap<String, String> ht = new HashMap<String, String>(); String fieldName = null;//from w ww.jav a 2 s .c om String fieldValue = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); java.util.List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fieldName = item.getFieldName(); fieldValue = item.getString(); ht.put(fieldName, fieldValue); } else if (!item.isFormField()) { UploadedFileBean bean = new UploadedFileBean(); bean.setFileItem(item); bean.setContentType(item.getContentType()); bean.setFileName(item.getName()); try { bean.setInputStream(item.getInputStream()); } catch (Exception e) { System.out.println("=== Erro: " + e); } bean.setIsInMemory(item.isInMemory()); bean.setSize(item.getSize()); fileBeanList.add(bean); request.getSession().setAttribute("UPLOADED_FILE", bean); } } } else if (!isMultipart) { Enumeration<String> en = request.getParameterNames(); String name = null; String value = null; while (en.hasMoreElements()) { name = en.nextElement(); value = request.getParameter(name); ht.put(name, value); } } request.setAttribute("REQUEST_PARAMETERS", ht); }
From source file:com.ephesoft.gxt.admin.server.ImportIndexFieldUploadServlet.java
/** * This API is used to process uploaded file and unzip file in export-batch-folder . * //from w w w . ja v a2s . co m * @param upload {@link ServletFileUpload} uploaded file. * @param req {@link HttpServletRequest}. * @param printWriter {@link PrintWriter}. * @param parentDirPath {@link String} to create absolute unzip directory path. * @return {@link File} temporary file after unzip. */ private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req, final PrintWriter printWriter, final String parentDirPath) { String tempUnZipDir = ""; String zipFileName = ""; String zipPathname = ""; File tempZipFile = null; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) { zipPathname = getZipPath(item, parentDirPath); zipFileName = getZipFileName(item); tempZipFile = copyItemContentInFile(item, zipPathname, printWriter); } } } catch (final FileUploadException e) { printWriter.write("Unable to read the form contents.Please try again."); } tempUnZipDir = parentDirPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempUnZipDir); if (!FileUtils.isDirectoryHasAllValidExtensionFiles(tempUnZipDir, SERIALIZATION_EXT)) { FileUtils.deleteQuietly(tempZipFile); FileUtils.deleteDirectoryAndContentsRecursive(new File(tempUnZipDir), true); tempUnZipDir = ""; log.error("Invalid zip file."); //throw new Exception(); } } catch (final Exception e) { printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } return tempUnZipDir; }
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w .j a v a 2 s .c o 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 */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BRAND_IMAGES_HOME; deletePath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("brandname")) { brandname = fi.getString(); } if (fieldName.equals("brandid")) { brandid = fi.getString(); } if (fieldName.equals("look")) { lookid = fi.getString(); } file_name_to_delete = brand.getFileName(Integer.parseInt(brandid)); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = brandname + "_" + Str + ".jpeg"; fileName = brandname + "_" + fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { out.close(); } }
From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /*www . j ava 2 s . co 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;// w w w . j ava 2 s . c om } //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.ikon.servlet.admin.CssServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); String userId = request.getRemoteUser(); updateSessionManager(request);/* w w w. ja va 2s . c o m*/ try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Css css = new Css(); css.setActive(false); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("css_id")) { if (!item.getString("UTF-8").isEmpty()) { css.setId(new Long(item.getString("UTF-8")).longValue()); } } else if (item.getFieldName().equals("css_name")) { css.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_context")) { css.setContext(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_content")) { css.setContent(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_active")) { css.setActive(true); } } } if (action.equals("edit")) { CssDAO.getInstance().update(css); // Activity log UserActivity.log(userId, "ADMIN_CSS_UPDATE", String.valueOf(css.getId()), null, css.getName()); } else if (action.equals("delete")) { String name = WebUtils.getString(request, "css_name"); CssDAO.getInstance().delete(css.getId()); // Activity log UserActivity.log(userId, "ADMIN_CSS_DELETE", String.valueOf(css.getId()), null, name); } else if (action.equals("create")) { long id = CssDAO.getInstance().create(css); // Activity log UserActivity.log(userId, "ADMIN_CSS_CREATE", String.valueOf(id), null, css.getName()); } } list(userId, request, response); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.ts.control.UploadFile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String campo1 = ""; String campo2 = ""; String campo3 = ""; String campo4 = ""; String campo5 = ""; String campo6 = ""; String campo7 = ""; int c = 1;// w ww. j av a2 s .co m try { boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (!ismultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { } else { String itemname = item.getName(); if ((itemname == null || itemname.equals(""))) { continue; } String filename = FilenameUtils.getName(itemname); System.out.println("ruta---------------" + saveFile + filename); File f = checkExist(filename); item.write(f); //////// List cellDataList = new ArrayList(); try { FileInputStream fileInputStream = new FileInputStream(f); XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream); XSSFSheet hssfSheet = workBook.getSheetAt(0); Iterator rowIterator = hssfSheet.rowIterator(); while (rowIterator.hasNext()) { XSSFRow hssfRow = (XSSFRow) rowIterator.next(); Iterator iterator = hssfRow.cellIterator(); List cellTempList = new ArrayList(); while (iterator.hasNext()) { XSSFCell hssfCell = (XSSFCell) iterator.next(); cellTempList.add(hssfCell); } cellDataList.add(cellTempList); } } catch (Exception e) { e.printStackTrace(); } out.println("<table border='3' class='table table-bordered table-striped table-hover'>"); for (int i = 1; i < cellDataList.size(); i++) { List cellTempList = (List) cellDataList.get(i); out.println("<tr>"); for (int j = 0; j < cellTempList.size(); j++) { XSSFCell hssfCell = (XSSFCell) cellTempList.get(j); String dato = hssfCell.toString(); out.print("<td>" + dato + "</td>"); switch (c) { case 1: campo1 = dato; c++; break; case 2: campo2 = dato; c++; break; case 3: campo3 = dato; c++; break; case 4: campo4 = dato; c++; break; case 5: campo5 = dato; c++; break; case 6: campo6 = dato; c++; break; case 7: campo7 = dato; c = 1; break; } } //model.Consulta.addRegistros(campo1,campo2,campo3,campo4,campo5,campo6,campo7); } out.println("</table><br>"); ///////// } } } } catch (Exception e) { } finally { out.close(); } }
From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java
/** * The doPost method of the servlet. <br> * /*w ww . j ava2s .c o m*/ * This method is called when a form has its tag value method equals to post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); String uid = (String) httpSession.getAttribute("uid"); if (uid == null || uid.isEmpty()) uid = "public"; String html = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!(item.isFormField())) { File eml = processUploadedFile(item); DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid); String xml = dpmClient.evaluateDataPackage(eml); ReportUtility qrUtility = new ReportUtility(xml); String htmlTable = qrUtility.xmlToHtmlTable(cwd + xslpath); if (htmlTable == null) { String msg = "The uploaded file could not be evaluated."; throw new UserErrorException(msg); } else { html = HTMLHEAD + "<div class=\"qualityreport\">" + htmlTable + "</div>" + HTMLTAIL; } } } } catch (Exception e) { handleDataPortalError(logger, e); } } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print(html); out.flush(); out.close(); }
From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java
/** * Process the uploaded file//from w w w . ja v a 2s.c om * * @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; }