List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:net.morphbank.mbsvc3.webservices.Uploader.java
/** * Process the fields in the form that are not FileItem * @param item/*from www. j a va 2 s.c om*/ */ private void processFormField(FileItem item) { if (item.getFieldName().equalsIgnoreCase("numLinesPerFile")) { numLines = Integer.parseInt(item.getString()); if (numLines < 100) { numLines = 100; } if (numLines > 700) { numLines = 700; } } if (item.getFieldName().equalsIgnoreCase("sendtoDB")) { if (item.getString().equalsIgnoreCase("send")) { sendToDB = true; } } }
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;//from w w w. ja v a 2s . co m 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;//from www . jav a2 s. c o m 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:es.sm2.openppm.core.plugin.action.GenericAction.java
/** * Find Multipart filed by name// ww w. j a va 2s . co m * * @param name - name of field * @return field in String format */ protected String getMultipartField(String name) { if (getMultipartFields() != null) { FileItem fileItem = getMultipartFields().get(name); if (fileItem != null) { return fileItem.getString(); } } return StringPool.BLANK; }
From source file:it.swim.servlet.profilo.azioni.RicerchePerUtentiLoggatiServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w ww . j a v a2 s. co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<FileItem> items; String nome = new String(); String cognome = new String(); String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request); List<Abilita> abilitaRicercate = new ArrayList<Abilita>(); List<Utente> risultatoRicerca = new ArrayList<Utente>(); boolean soloAmici = false; ricerca = false; 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("nomeUtente")) { nome = item.getString().trim(); } if (item.getFieldName().equals("cognomeUtente")) { cognome = item.getString().trim(); } if (item.getFieldName().equals("abilita")) { abilitaRicercate.add(registrazione.getAbilitaByNome(item.getString())); } if (item.getFieldName().equals("soloAmici")) { soloAmici = true; } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (tipoRicerca.equals("aiuto")) { try { risultatoRicerca = gestioneRicerche.ricercaAiuto(abilitaRicercate, (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request)); if (soloAmici == true) { List<Utente> amiciUtente = gestioneAmicizie.getAmici(emailUtenteCollegato); for (int i = 0; i < risultatoRicerca.size(); i++) { if (!(amiciUtente.contains(risultatoRicerca.get(i)))) { risultatoRicerca.remove(i); i--; } } } } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("abilita", gestioneRicerche.insiemeAbilitaGenerali()); request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); request.setAttribute("tipoRicerca", tipoRicerca); } else if (tipoRicerca.equals("aiutoVisitatore")) { try { risultatoRicerca = gestioneRicerche.ricercaAiutoVisitatore(abilitaRicercate); } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("abilita", gestioneRicerche.insiemeAbilitaGenerali()); request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); request.setAttribute("tipoRicerca", tipoRicerca); } else { try { risultatoRicerca = gestioneRicerche.ricercaUtenti(nome, cognome, (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request)); } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("tipoRicerca", tipoRicerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); } getServletConfig().getServletContext().getRequestDispatcher("/jsp/ricerche.jsp").forward(request, response); }
From source file:Controller.Publicacion.java
private String uploadFile(HttpServletRequest request) { String imageName = "", textfield = ""; String archivourl = "C:\\xampp\\htdocs\\RedSocial\\web\\files"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000 * 1024); factory.setRepository(new File(archivourl)); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from ww w . ja v a 2 s . com*/ List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); String inputName = null; for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); item.write(new File(archivourl + File.separator + name)); imageName = name; } if (item.isFormField()) { inputName = (String) item.getFieldName(); if (inputName.equalsIgnoreCase("cont")) { textfield = (String) item.getString(); imageName = textfield; } } } } catch (Exception e) { } return imageName; }
From source file:calliope.handler.post.AeseImportHandler.java
/** * Parse the import params from the request * @param request the http request/* w w w . j a v a 2 s . c o m*/ */ void parseImportParams(HttpServletRequest request) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(); if (fieldName.equals(Params.DOCID)) { if (contents.startsWith("/")) { contents = contents.substring(1); int pos = contents.indexOf("/"); if (pos != -1) { database = contents.substring(0, pos); contents = contents.substring(pos + 1); } } docID = new DocID(contents); } else if (fieldName.startsWith(Params.SHORT_VERSION)) nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString()); else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)) { jsonKeys.put(fieldName.toLowerCase(), contents); style = contents; } else if (fieldName.equals(Params.DEMO)) { if (contents != null && contents.equals("brillig")) demo = false; else demo = true; } else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.FILTER)) filterName = contents.toLowerCase(); else if (fieldName.equals(Params.SIMILARITY)) similarityTest = contents != null && contents.equals("1"); else if (fieldName.equals(Params.SPLITTER)) splitterName = contents; else if (fieldName.equals(Params.STRIPPER)) stripperName = contents; else if (fieldName.equals(Params.TEXT)) textName = contents.toLowerCase(); else if (fieldName.equals(Params.XSLT)) xslt = getConfig(Config.xslt, contents); else if (fieldName.equals(Params.DICT)) dict = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.HH_EXCEPTIONS)) hhExceptions = contents; else jsonKeys.put(fieldName, contents); } } else if (item.getName().length() > 0) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null && type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); images.add(iFile); } else { byte[] rawData = item.get(); guessEncoding(rawData); //System.out.println(encoding); File f = new File(item.getName(), new String(rawData, encoding)); files.add(f); } } catch (Exception e) { throw new AeseException(e); } } } if (style == null) style = DEFAULT_STYLE; } catch (Exception e) { throw new AeseException(e); } // System.out.println("Import params received:"); // System.out.println("docID="+docID.get()); // System.out.println("style="+style); // System.out.println("filterName="+filterName); // System.out.println("database="+database); // System.out.println("splitterName="+splitterName); // System.out.println("stripperName="+stripperName); // System.out.println("encoding="+encoding); // System.out.println("hhExceptions="+hhExceptions); // System.out.println("similarityTest="+similarityTest); // System.out.println("dict="+dict); // System.out.println("xslt="+xslt); // System.out.println("demo="+demo); // System.out.println("textName="+textName); }
From source file:com.sun.faban.harness.webclient.RunUploader.java
/** * Post method to upload the run.// ww w.ja v a 2s. c om * @param request The servlet request * @param response The servlet response * @throws ServletException If the servlet fails * @throws IOException If there is an I/O error */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. Origin file" + "does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin host " + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) { uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); break; } }
From source file:controller.EditProfileController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*w w w. ja va2 s .c om*/ DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); if (user == null) { user = new User(); } ArrayList<String> newInterests = new ArrayList<>(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { user.setImage(image); } // System.out.println(user.getImage()); } else { switch (item.getFieldName()) { case "name": user.setUserName(item.getString()); break; case "mail": user.setEmail(item.getString()); break; case "password": user.setPassword(item.getString()); break; case "job": user.setJob(item.getString()); break; case "date": DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(item.getString(), formatter); user.setDOB(date); break; case "address": user.setAddress(item.getString()); break; case "credit": user.setCreditNumber(item.getString()); break; default: newInterests.add(item.getString()); // System.out.println(item.getFieldName() + " : " + item.getString()); } } } user.setInterests(newInterests); UserDaoImpl userDao = new UserDaoImpl(); userDao.updateUser(user); session.setAttribute("user", user); // System.out.println(user.getInterests()); // System.out.println(user.getImage()); } catch (FileUploadException ex) { Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("profile.jsp"); }
From source file:eg.agrimarket.controller.EditProfileController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* ww w .ja v a2s.c o m*/ DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); if (user == null) { user = new User(); } ArrayList<Interest> newInterests = new ArrayList<>(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { user.setImage(image); } // System.out.println(user.getImage()); } else { switch (item.getFieldName()) { case "name": user.setUserName(item.getString()); break; case "mail": user.setEmail(item.getString()); break; case "password": user.setPassword(item.getString()); break; case "job": user.setJob(item.getString()); break; case "date": DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(item.getString(), formatter); user.setDOB(date); break; case "address": user.setAddress(item.getString()); break; case "credit": user.setCreditNumber(item.getString()); break; default: eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest(); interest.setId(Integer.parseInt(item.getString())); interest.setName(item.getFieldName()); newInterests.add(interest); System.out.println(item.getFieldName() + " : " + item.getString()); } } } user.setInterests(newInterests); UserDaoImpl userDao = new UserDaoImpl(); userDao.updateUser(user); session.setAttribute("user", user); } catch (FileUploadException ex) { Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("profile.jsp"); }