List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:adminpackage.adminview.UpdateProductServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String value = "defa"; AdminUpdateProductWrapper product = new AdminUpdateProductWrapper(); try {/* www . ja va 2 s . c o m*/ DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator itr = items.iterator(); String url = ""; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { String name = item.getFieldName(); value = item.getString(); switch (name) { case "pid": product.setId(Integer.parseInt(value)); break; case "pname": product.setName(value); break; case "quantity": product.setQuantity(Integer.parseInt(value)); break; case "author": product.setAuthor(value); break; case "isbn": product.setISBN(Long.parseLong(value)); break; case "description": product.setDescription(value); break; case "category": product.setCategory(value); break; case "price": product.setPrice(Integer.parseInt(value)); break; } } else { try { if (item.getName().length() > 0) { item.write(new File(context.getRealPath("/pages/images/").replaceAll( "\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName())); //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName()); //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName(); UUID idOne = UUID.randomUUID(); product.setImage( idOne.toString() + item.getName().substring(item.getName().length() - 4)); } } catch (Exception ex) { Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex); } } } } catch (FileUploadException ex) { Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("adminpackage.adminview.UpdateProductServlet.processRequest()"); out.print(adminFacadeHandler.UpdateProduct(product)); if (value != null) { } }
From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java
@SuppressWarnings("rawtypes") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestContext ctx = new ServletRequestContext(req); String enc = ctx.getCharacterEncoding(); logger.warn("received encoding is " + enc); if (enc == null) { enc = "utf-8"; }/* w ww. jav a 2s . co m*/ IAccount account = (IAccount) req.getSession().getAttribute("account"); if (account == null) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(20 * 1024 * 1024); List items = null; try { items = upload.parseRequest(req); } catch (FileUploadException e1) { logger.error("upload exception", e1); return; } // Process the uploaded items String id = null; Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { id = item.getFieldName(); String fileName = removePathElementsFromFilename(item.getName()); logger.warn("FileItem: " + item); long size = item.getSize(); logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@" + account.getDomain() + " size: " + size + ")."); AttachmentMetadata meta = new AttachmentMetadata(); meta.setFileName(fileName); meta.setSize(size); meta.setMime(item.getContentType()); try { account.uploadAttachement(id, meta, item.getInputStream()); } catch (Exception e) { logger.error("Cannot write uploaded file to disk"); } } } }
From source file:com.colegiocefas.cefasrrhh.servlets.subirImagen.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from www .j a va 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ajaxUpdateResult = "Error"; try { List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { } else { Date fecha = Calendar.getInstance().getTime(); SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-"); String nombreImagen = formato.format(fecha); HttpSession sesionOk = request.getSession(); String usuario = (String) sesionOk.getAttribute("usuario"); if (usuario == null) { request.getRequestDispatcher("index.jsp").forward(request, response); return; } nombreImagen += usuario; //String fileName = item.getName(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String realPath = request.getSession().getServletContext().getRealPath("/"); File fichero = new File(realPath + "img/fotos/", nombreImagen + ".png"); item.write(fichero); ajaxUpdateResult = "img/fotos/" + fichero.getName(); } } } catch (Exception e) { ajaxUpdateResult = "ErrorException"; throw new ServletException("Parsing file upload failed.", e); } response.getWriter().print(ajaxUpdateResult); }
From source file:ned.bcvs.admin.fileupload.ConstituencyFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;/*from ww w.j av a2s .co m*/ } 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( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet 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(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = 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 Filename: " + fileName + "<br>"); } } //calling the ejb method to save constituency.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "constituency")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww 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 { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } //Init Jpa CategoryJpaController categoryJpa = new CategoryJpaController(emf); StyleJpaController styleJpa = new StyleJpaController(emf); ProjectJpaController projectJpa = new ProjectJpaController(emf); IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf); // get Object Category by categoryId int cateId = Integer.parseInt((String) params.get("ddlCategory")); Category cate = categoryJpa.findCategory(cateId); // get Object Style by styleId int styleId = Integer.parseInt((String) params.get("ddlStyle")); Style style = styleJpa.findStyle(styleId); // get Object Project by projectId int projectId = Integer.parseInt((String) params.get("txtProjectId")); Project project = projectJpa.findProject(projectId); project.setStatus(Constant.STATUS_WAIT); projectJpa.edit(project); //Get param String title = (String) params.get("title"); String description = (String) params.get("description"); String url = "images/" + fileName; //Init IdeabookPhoto IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project); photoJpa.create(photo); url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId; //System HDSystem system = new HDSystem(); system.setNotificationProject(request); response.sendRedirect(url); } } catch (Exception e) { log("Error at AddImageToProjectServlet: " + e.getMessage()); } finally { out.close(); } }
From source file:ned.bcvs.admin.fileupload.ElectionPartyFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;/* w w w . j av a 2s. co m*/ } 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( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet 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 sizeInBytes = 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 Filename: " + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "electionparty")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:ned.bcvs.admin.fileupload.ConstituencyTypeFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;//from w w w .j a v a2 s . c om } 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( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet 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(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = 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 Filename: " + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base System.out.println("%%%%%%% " + filePath + fileName); out.println(upbean.fileDbUploader(filePath + fileName, "constituencytype")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.example.web.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); //response.setContentType("text/html"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;/*from w ww . jav a2 s .c om*/ } 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("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet 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 sizeInBytes = 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 Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.controller.UploadLogo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//www .j a v a2 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 */ @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(); getSqlMethodsInstance().session = request.getSession(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, uploadType = null; RequestDispatcher request_dispatcher = null; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.USER_LOGO; // 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(); boolean ch = fi.isFormField(); if (!fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); fileName = fi.getName(); String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID"); int UID = getSqlMethodsInstance().getUserID(uid); uploadPath = uploadPath + File.separator + UID + File.separator + "logo"; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = Str + "_" + UID + ".jpeg"; fileName = fileName + "_" + UID; getSqlMethodsInstance().session.setAttribute("UID", UID); getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); getSqlMethodsInstance().updateUsers(UID, fileName); out.println("Uploaded Filename: " + filePath + "<br>"); } } } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); getSqlMethodsInstance().closeConnection(); } }
From source file:eg.agrimarket.controller.ProductController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from www.j a v a2 s. c om*/ PrintWriter out = response.getWriter(); eg.agrimarket.model.pojo.Product product = new eg.agrimarket.model.pojo.Product(); Product productJPA = new Product(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { product.setImage(image); productJPA.setImage(image); } } else { switch (item.getFieldName()) { case "name": product.setName(item.getString()); productJPA.setName(item.getString()); System.out.println("name" + item.getString()); break; case "price": product.setPrice(Float.valueOf(item.getString())); productJPA.setPrice(Float.valueOf(item.getString())); break; case "quantity": product.setQuantity(Integer.valueOf(item.getString())); productJPA.setQuantity(Integer.valueOf(item.getString())); break; case "desc": product.setDesc(item.getString()); productJPA.setDesc(item.getString()); System.out.println("desc: " + item.getString()); break; default: Category category = new Category(); category.setId(Integer.valueOf(item.getString())); product.setCategoryId(category); productJPA.setCategoryId(category.getId()); } } } ProductDao daoImp = new ProductDaoImp(); boolean check = daoImp.addProduct(product); if (check) { List<Product> products = (List<Product>) request.getServletContext().getAttribute("products"); if (products != null) { products.add(productJPA); request.getServletContext().setAttribute("products", products); } response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort() + "/AgriMarket/admin/getProducts?success=Successfully#header3-41"); } else { response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort() + "/AgriMarket/admin/getProducts?status=Exist!#header3-41"); } } catch (FileUploadException ex) { Logger.getLogger(ProductController.class.getName()).log(Level.SEVERE, null, ex); } }