List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:controller.Upload.java
/** * Servlet implementation class UploadServlet *//*from w w w . jav a 2s . c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // constructs the folder where uploaded file will be stored String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); String fileName = "", newname = ""; try { // Parse the request List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { // fileName = (String)session.getId() + new File(item.getName()).getName(); // String filePath = uploadFolder + File.separator + fileName; fileName = new File(item.getName()).getName(); newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf(".")); String filePath = uploadFolder + File.separator + newname; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory item.write(uploadedFile); } } userDao ud = new userDao(); ud.changeuserpic((int) session.getAttribute("userID"), newname); // displays done.jsp page after upload finished getServletContext().getRequestDispatcher("/done.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:de.fau.amos.FileUpload.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); System.out.println("called fileupload: " + pathInfo); boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData"); boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData"); if (ServletFileUpload.isMultipartContent(request)) { try {/*from www .j a v a2 s . c om*/ List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem fi : list) { if (!fi.isFormField()) { String rand = ""; for (int i = 0; i < 6; i++) { rand += (int) (Math.random() * 10); } String plantId = ""; if (isImportEnergyData || isImportProductionData) { plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData" : (isImportProductionData ? "/importProductionData" : "")), ""); } if (plantId == null || plantId.length() == 0) { plantId = ""; // }else{ // plantId="_"+plantId; } String name = new File(rand + "_" + fi.getName()).getName() + (isImportEnergyData ? "_impED" + plantId : (isImportProductionData ? "_impPD" + plantId : "")); File folder = null; if (isImportEnergyData || isImportProductionData) { folder = new File(System.getProperty("userdir.location"), "import"); } else { folder = new File(System.getProperty("userdir.location"), "uploads"); } if (!folder.exists()) { folder.mkdirs(); } fi.write(new File(folder, name)); } } request.setAttribute("message", "File uploaded successfully"); } catch (Exception e) { request.setAttribute("errorMessage", "File upload failed!"); } } else { request.setAttribute("errorMessage", "Something went wrong."); } if (isImportEnergyData || isImportProductionData) { // request.setAttribute("plant",request.getPathInfo().replace("/import","")); // request.getRequestDispatcher("/intern/import.jsp").forward(request, response); response.sendRedirect(request.getContextPath() + "/intern/import.jsp"); } else { response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp"); } }
From source file:dk.netarkivet.harvester.webinterface.TrapCreateOrUpdateAction.java
@Override protected void doAction(PageContext context, I18n i18n) { String name = null;/*from ww w. j a v a 2 s . co m*/ boolean isActive = true; String description = null; InputStream is = null; String id = null; String fileName = null; HttpServletRequest request = (HttpServletRequest) context.getRequest(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error"); throw new ForwardedToErrorPage("Error on multipart post", e); } for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals(Constants.TRAP_NAME)) { name = item.getString(); } else if (item.getFieldName().equals(Constants.TRAP_IS_ACTIVE)) { isActive = Boolean.parseBoolean(item.getString()); } else if (item.getFieldName().equals(Constants.TRAP_DESCRIPTION)) { description = item.getString(); } else if (item.getFieldName().equals(Constants.TRAP_ID)) { id = item.getString(); } } else { try { fileName = item.getName(); is = item.getInputStream(); } catch (IOException e) { HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error"); throw new ForwardedToErrorPage("Error on multipart post", e); } } } GlobalCrawlerTrapListDAO dao = GlobalCrawlerTrapListDBDAO.getInstance(); if (id != null) { // update existing trap list int trapId = Integer.parseInt(id); GlobalCrawlerTrapList trap = dao.read(trapId); trap.setActive(isActive); trap.setDescription(description); trap.setName(name); if (fileName != null && !fileName.isEmpty()) { log.debug("Reading global crawler trap list from '" + fileName + "'"); try { trap.setTrapsFromInputStream(is, name); } catch (ArgumentNotValid argumentNotValid) { HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.regexp.error"); throw new ForwardedToErrorPage(argumentNotValid.getMessage()); } } dao.update(trap); } else { // create new trap list log.debug("Reading global crawler trap list from '" + fileName + "'"); GlobalCrawlerTrapList trap = new GlobalCrawlerTrapList(is, name, description, isActive); if (!dao.exists(name)) { dao.create(trap); } else { // crawlertrap named like this already exists. HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.0.exists.error", name); throw new ForwardedToErrorPage("Crawlertrap with name '" + name + "' exists already"); } } }
From source file:com.jkthome.cmm.web.JkthomeMultipartResolver.java
/** * multipart? parsing? ./* w w w . j ava 2 s. c o m*/ */ @SuppressWarnings("rawtypes") @Override protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { //? 3.0 MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); // Extract multipart files and multipart parameters. for (Iterator<?> it = fileItems.iterator(); it.hasNext();) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { String value = null; if (encoding != null) { try { value = fileItem.getString(encoding); } catch (UnsupportedEncodingException ex) { LOGGER.warn( "Could not decode multipart item '{}' with encoding '{}': using platform default", fileItem.getFieldName(), encoding); value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } } else { if (fileItem.getSize() > 0) { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); //? 3.0 ? API? List<MultipartFile> fileList = new ArrayList<MultipartFile>(); fileList.add(file); if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!! throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); } LOGGER.debug( "Found multipart file [{}] of size {} bytes with original filename [{}], stored {}", file.getName(), file.getSize(), file.getOriginalFilename(), file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters, null); }
From source file:edu.brown.cs32.siliclone.servlets.SampleUploadServlet.java
/** * Override executeAction to save the received files in a custom place * and delete this items from session. *//* w w w .j a v a 2s . co m*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { System.out.println("RUNNING EXECUTE ACTION"); for (FileItem item : sessionFiles) { System.out.println("looping"); if (false == item.isFormField()) { try { /// Create a new file based on the remote file name in the client // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // File file =new File("/tmp/" + saveName); /// Create a temporary file // File file = File.createTempFile("upload-", ".bin", new File("/tmp")); File file = File.createTempFile("upload-", ".bin"); item.write(file); receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); } catch (Exception e) { throw new UploadActionException(e.getMessage()); } } removeSessionFileItems(request); } return null; }
From source file:FileUploading.UploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(req); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); if (!isMultipart) { String title = ""; out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("<body>"); out.println("<body>"); out.println("<p> No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;// ww w. ja v a2 s . c o m } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in the memory factory.setSizeThreshold(maxMemSize); // location to save data that is larger than maxMemsize factory.setRepository(new File("C:\\temp")); //create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //maximum file size to be upload upload.setSizeMax(maxFileSize); try { //parse the requset to get file items List fileItems = upload.parseRequest(req); // process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servket Upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { //get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInMemory = fi.getSize(); //write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded file name : " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception e) { } }
From source file:net.daw.control.upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = ""; String strMessage = ""; HashMap<String, String> hash = new HashMap<>(); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(".//..//webapps//images//" + name)); } else { hash.put(item.getFieldName(), item.getString()); } } Gson oGson = new Gson(); Map<String, String> data = new HashMap<>(); Iterator it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); data.put(e.getKey().toString(), e.getValue().toString()); } data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + name); out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}"); } catch (Exception ex) { strMessage += "File Upload Failed: " + ex; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } else { strMessage += "Only serve file upload requests"; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } }
From source file:ar.com.easytech.faces.filters.MultipartRequest.java
@SuppressWarnings("unchecked") public MultipartRequest(HttpServletRequest request, String path) throws Exception { super(request); DiskFileItemFactory factory = new DiskFileItemFactory(); if (path != null) factory.setRepository(new File(path)); ServletFileUpload upload = new ServletFileUpload(factory); parameterMap.put("path", path); try {/* w ww .j a v a 2 s.c om*/ List<FileItem> items = (List<FileItem>) upload.parseRequest(request); for (FileItem item : items) { String str = item.getString(); if (item.isFormField()) parameterMap.put(item.getFieldName(), str); else { if (item.getName() != null) { parameterMap.put("fileName", item.getName()); } request.setAttribute(item.getFieldName(), item); } } } catch (FileUploadException ex) { ServletException servletEx = new ServletException(); servletEx.initCause(ex); throw new Exception(ex.getLocalizedMessage()); } }
From source file:com.shyslav.controller.UploadController.java
@RequestMapping(value = "/uploadAction") private String uploadAction(ModelMap mv, RedirectAttributes redirectAttributes, HttpSession ses, HttpServletRequest request) throws URISyntaxException { String name = null;//from w w w.j a v a 2s . co m String genre = null; String author = null; String smallText = null; String fullText = null; String vision = null; String serverPath = null; Properties props = new Properties(); try (InputStream in = UploadController.class.getResourceAsStream("application.properties")) { props.load(in); } catch (IOException ex) { System.out.println(ex); } DiskFileItemFactory d = new DiskFileItemFactory(); ServletFileUpload uploadre = new ServletFileUpload(d); System.out.println(props.getProperty("downloadDirectory")); try { List<FileItem> list = uploadre.parseRequest(request); for (FileItem f : list) { if (f.isFormField() == false) { //write file to upload folder; if (!FilenameUtils.getExtension(f.getName()).equals("pdf")) { String ext = FilenameUtils.getExtension(f.getName()); System.out.println(ext); System.out.println("comed"); redirectAttributes.addFlashAttribute("error", "? ? , ? pdf"); return "redirect:add.htm"; } serverPath = "/" + author + "_" + name + "_" + genre + "_" + Math.random() * 100 + "." + FilenameUtils.getExtension(f.getName()); f.write(new File(props.getProperty("downloadDirectory") + serverPath)); System.out.println(f.getName()); } else if (f.isFormField()) { String fieldname = f.getFieldName(); if (fieldname.equals("name")) { name = f.getString("UTF-8"); } else if (fieldname.equals("genre")) { genre = f.getString("UTF-8"); } else if (fieldname.equals("author")) { author = f.getString("UTF-8"); } else if (fieldname.equals("smallText")) { smallText = f.getString("UTF-8"); } else if (fieldname.equals("fullText")) { fullText = f.getString("UTF-8"); } else if (fieldname.equals("vision")) { vision = f.getString("UTF-8"); } System.out.println(f.getFieldName().toString()); } } } catch (Exception ex) { System.out.println(ex); } if (name == null || genre == null || author == null || smallText == null || fullText == null || vision == null || smallText.length() < 30 || fullText.length() < 50 || name.length() < 3) { redirectAttributes.addFlashAttribute("error", "? ? ? "); return "redirect:add.htm"; } try { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Query query = session.createSQLQuery("INSERT INTO books\n" + "(name, author, genre, small_text, full_text, date_create, vision, server_Path)\n" + "VALUES('" + name + "', '" + author + "', " + genre + ", '" + smallText + "', '" + fullText + "', NOW(), '" + vision + "','" + serverPath + "')"); System.out.println(query.toString()); int result = query.executeUpdate(); session.getTransaction().commit(); } catch (Exception ex) { System.out.println(ex); } redirectAttributes.addFlashAttribute("sucses", " ? "); return "redirect:index.htm"; }
From source file:it.swim.servlet.profilo.azioni.RilasciaFeedBackServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from w w w . jav a 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); }