List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:edu.temple.cis3238.wiki.ui.servlets.UploaderServlet.java
/** * Processes requests for HTTP <code>POST</code> method. * * @param request servlet request//w ww. ja v a 2 s . co m * @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"); try (PrintWriter out = response.getWriter()) { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must be enctype = multipart/form-data."); writer.flush(); setSuccess(false); return; } // configures upload settings 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); if (request.getSession() != null && request.getSession().getAttribute("topicCollection") != null) { try { collection = (TopicCollection) request.getSession().getAttribute("topicCollection"); setTopic(collection.getCurrentTopic()); setTopicID(getTopic().getTopicID() + ""); } catch (Exception e) { e.printStackTrace(); if (getTopic() == null) { try { setTopicID(request.getSession().getAttribute("topicID").toString()); setTopic(new TopicVOBuilder().setTopicID(Integer.parseInt(getTopicID())).build()); } catch (Exception ex) { ex.printStackTrace(); } } } } else { setTopicID("none"); } String uploadPath = FileUtils.makeDir(getServletContext(), UPLOAD_DIRECTORY, getTopic()); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); String fileName = ""; if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; System.out.println(filePath); File storeFile = new File(filePath); if (FileUtils.checkFileExtension(storeFile.getName().toLowerCase(), null)) { item.write(storeFile); request.setAttribute("sourceFile", fileName); System.out.println("----------------------------"); System.out.println("FILENAME is :" + fileName); System.out.println("----------------------------"); request.setAttribute("topicID", StringUtils.toS(getTopicID())); setStatus(request, true, "Success: Topic " + StringUtils.toS(getTopicID()) + " has saved file " + fileName + ". Upload has been done successfully!"); } else { setStatus(request, false, "Exception: Invalid file extension"); } } } } else { setStatus(request, false, "Exception: No valid file(s)"); } } catch (Exception ex) { ex.printStackTrace(); setStatus(request, false, "Exception: " + StringUtils.coalesce(ex.getMessage(), ex.toString(), "unknown")); } // redirects client to message page getServletContext().getRequestDispatcher("/" + REDIRECT_ON_COMPLETE_PAGE).forward(request, response); } }
From source file:it.lufraproini.cms.servlet.Upload.java
private Map prendiInfo(HttpServletRequest request) throws FileUploadException { Map info = new HashMap(); Map files = new HashMap(); //riutilizzo codice prof. Della Penna per l'upload if (ServletFileUpload.isMultipartContent(request)) { // Funzioni delle librerie Apache per l'upload FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; items = upload.parseRequest(request); ///* w w w . ja va 2s . co m*/ for (FileItem item : items) { String name = item.getFieldName(); //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo if (name.startsWith("file_to_upload")) { files.put(name, item); } else { info.put(name, item.getString()); } } info.put("files", files); return info; } return null; }
From source file:com.acciente.commons.htmlform.Parser.java
private static Map parsePOSTMultiPart(HttpServletRequest oRequest, int iStoreFileOnDiskThresholdInBytes, File oUploadedFileStorageDir) throws FileUploadException, IOException, ParserException { Map oMultipartParams = new HashMap(); // we have multi-part content, we process it with apache-commons-fileupload ServletFileUpload oMultipartParser = new ServletFileUpload( new DiskFileItemFactory(iStoreFileOnDiskThresholdInBytes, oUploadedFileStorageDir)); List oFileItemList = oMultipartParser.parseRequest(oRequest); for (Iterator oIter = oFileItemList.iterator(); oIter.hasNext();) { FileItem oFileItem = (FileItem) oIter.next(); // we support the variable name to use the full syntax allowed in non-multipart forms // so we use parseParameterSpec() to support array and map variable syntaxes in multi-part mode Reader oParamNameReader = null; ParameterSpec oParameterSpec = null; try {//from w w w . j a v a 2s . c o m oParamNameReader = new StringReader(oFileItem.getFieldName()); oParameterSpec = Parser.parseParameterSpec(oParamNameReader, oFileItem.isFormField() ? Symbols.TOKEN_VARTYPE_STRING : Symbols.TOKEN_VARTYPE_FILE); } finally { if (oParamNameReader != null) { oParamNameReader.close(); } } if (oFileItem.isFormField()) { Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem.getString(), false); } else { Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem); } } return oMultipartParams; }
From source file:com.ccsna.safetynet.AdminNewsServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j ava2 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 { response.setContentType("text/html;charset=UTF-8"); try { PrintWriter out = response.getWriter(); String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "", endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null; Date sDate = null, eDate = null; Time eTime = null, sTime = null; String fullPath = null; int action = 0, newsId = 0; boolean dataValid = true; News news = null; Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession()); if (loggedInMember != null) { String home = ""; String alertPage = ""; if (loggedInMember.getRole().equals(Menu.MEMBER)) { home = "/pages/member.jsp"; alertPage = "/pages/memberAlert.jsp"; } else { home = "/pages/agencyAdmin.jsp"; alertPage = "/pages/editAlert.jsp"; } log.info("home page is : " + home); log.info("alert page is : " + alertPage); String createdBy = String.valueOf(loggedInMember.getMemberId()); boolean isMultipart = ServletFileUpload.isMultipartContent(request); log.info("isMultipart :" + isMultipart); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String appPath = request.getServletContext().getRealPath(""); //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot"; //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/"; try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { //log.info("item is form field"); String fileName = item.getName(); //log.info("the name of the item is :" + fileName); String contentType = item.getContentType(); //log.info("the content type is :" + contentType); if (item.getContentType().equalsIgnoreCase(JPEG) || item.getContentType().equalsIgnoreCase(JPG) || item.getContentType().equalsIgnoreCase(PDF)) { String root = appPath; log.info("pdf content recognised"); log.info("root path is :" + appPath); //String smallLoc = "/uploads/small"; String largeLoc = "/uploads/large"; log.info("largeLoc:" + largeLoc); //File pathSmall = new File(root + smallLoc); File pathLarge = new File(root + largeLoc); //log.info("small image path :" + pathSmall); log.info("large image path :" + pathLarge); if (!pathLarge.exists()) { // boolean status = pathSmall.mkdirs(); pathLarge.mkdirs(); } if (item.getContentType().equalsIgnoreCase(PDF)) { log.info("loading pdf file"); fileType = Menu.PDF; fileName = createdBy + "_" + System.currentTimeMillis() + "." + PDF_EXTENSION; //File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge); } else { fileType = Menu.IMAGE; fileName = createdBy + "_" + System.currentTimeMillis() + "." + JPEG_EXTENSION; log.info("filename is : " + fileName); // File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall); Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge); } //smallUrl = smallLoc + "/" + fileName + ""; largeUrl = largeLoc + "/" + fileName + ""; log.info("largeUrl image url is :" + largeUrl); fullPath = request.getContextPath() + "/" + largeUrl; } } else { if (item.getFieldName().equalsIgnoreCase("newsTitle")) { title = item.getString(); log.info("title is :" + title); } if (item.getFieldName().equalsIgnoreCase("type")) { newsType = item.getString(); log.info("newsType is :" + newsType); } if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); log.info("content is :" + content); } if (item.getFieldName().equalsIgnoreCase("start_Date")) { startDate = item.getString(); if (startDate != null && !startDate.isEmpty()) { sDate = Menu .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd")); } log.info("startDate is :" + startDate); } if (item.getFieldName().equalsIgnoreCase("end_Date")) { endDate = item.getString(); if (endDate != null && !endDate.isEmpty()) { eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd")); } log.info("endDate is :" + endDate); } if (item.getFieldName().equalsIgnoreCase("action")) { action = Integer.parseInt(item.getString()); log.info("the action is :" + action); } if (item.getFieldName().equalsIgnoreCase("newsId")) { newsId = Integer.parseInt(item.getString()); log.info("the newsid is :" + newsId); } if (item.getFieldName().equalsIgnoreCase("status")) { st = item.getString(); log.info("the status is :" + st); } if (item.getFieldName().equalsIgnoreCase("end_Time")) { endTime = item.getString(); if (endTime != null && !endTime.isEmpty()) { eTime = Menu.convertStringToSqlTime(endTime); } log.info("eTime is :" + eTime); } if (item.getFieldName().equalsIgnoreCase("start_Time")) { startTime = item.getString(); if (startTime != null && !startTime.isEmpty()) { sTime = Menu.convertStringToSqlTime(startTime); } log.info("sTime is :" + sTime); } } } } catch (FileUploadException e) { e.printStackTrace(); } } switch (Validation.Actions.values()[action]) { case CREATE: log.info("creating new serlvet ................"); news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy, Menu.ACTIVE, largeUrl, fileType, fullPath); if (news != null) { log.info("news successfully created..."); message += "News item has been successfully added"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + home); } else { log.info("news creating failed..."); message += "Unable to add news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + home); } break; case UPDATE: log.info("updating news ..."); if (title != null && !title.isEmpty()) { news = new NewsModel().findByParameter("title", title); } if (news != null && (news.getNewsId() == newsId)) { log.info("news is :" + news.getNewsId()); dataValid = true; } else { dataValid = false; } if (news == null) { dataValid = true; } log.info("dataValid is :" + dataValid); if (dataValid) { boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate, eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime); if (newsUpdated) { message += "News/Alert has been successfully updated"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + home); } else { message += "Unable to update news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId); } } else { message += "News with same title already exist, Enter a different title"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId); } break; } } else { message += "Session expired, Kindly login with username and password"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/index.jsp"); } } catch (Exception e) { } }
From source file:com.ikon.servlet.WorkflowRegisterServlet.java
@SuppressWarnings("unchecked") private String handleRequest(HttpServletRequest request) throws FileUploadException, IOException, Exception { log.debug("handleRequest({})", request); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); if (items.isEmpty()) { String msg = "No process file in the request"; log.warn(msg);/* w w w.j a va 2 s . c o m*/ return msg; } else { FileItem fileItem = (FileItem) items.get(0); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { String msg = "Not a process archive"; log.warn(msg); throw new Exception(msg); } else { log.info("Deploying process archive: {}", fileItem.getName()); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); InputStream isForms = null; ZipInputStream zis = null; try { zis = new ZipInputStream(fileItem.getInputStream()); ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zis); // Check XML form definition FileDefinition fileDef = processDefinition.getFileDefinition(); isForms = fileDef.getInputStream("forms.xml"); FormUtils.parseWorkflowForms(isForms); log.debug("Created a processdefinition: {}", processDefinition.getName()); jbpmContext.deployProcessDefinition(processDefinition); return "Process " + processDefinition.getName() + " deployed successfully"; } finally { IOUtils.closeQuietly(isForms); IOUtils.closeQuietly(zis); jbpmContext.close(); } } } } else { log.warn("Not a multipart request"); return "Not a multipart request"; } }
From source file:it.fub.jardin.server.Upload.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) /* throws ServletException, IOException */ { try {/*from w w w . j a v a 2 s. c o m*/ this.dbProperties = new DbProperties(); } catch (VisibleException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.dbConnectionHandler = this.dbProperties.getConnectionHandler(); try { this.dbUtils = new DbUtils(dbProperties, dbConnectionHandler); } catch (VisibleException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.mailUtility = new MailUtility(dbConnectionHandler.getDbConnectionParameters().getMailSmtpHost(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpAuth(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpUser(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpPass(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpSender(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpSysadmin()); subSystem = dbConnectionHandler.getDbConnectionParameters().getSubSystem(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_SIZE); String m = null; try { // Parse the request 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()) { this.processFormField(item); } else { m = this.processUploadedFile(item); } } response.setContentType("text/plain"); response.getWriter().write(m); } catch (Exception e) { // Log.warn("Errore durante l'upload del file", e); } }
From source file:Controllers.EditItem.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww .j av a2 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 id = null; String name = null; String itemCode = null; String price = null; String quantity = null; String category = null; String image = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login"); return; } // request.getServletContext().getRealPath("/uploads"); String path = request.getServletContext().getRealPath("/uploads"); System.out.println(path); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); // new File(path).mkdirs(); File directory = new File(path + File.separator + fileName); image = fileName; item.write(directory); } else { if ("name".equals(item.getFieldName())) { name = item.getString(); } else if ("id".equals(item.getFieldName())) { id = item.getString(); } else if ("itemCode".equals(item.getFieldName())) { itemCode = item.getString(); } else if ("price".equals(item.getFieldName())) { price = item.getString(); } else if ("quantity".equals(item.getFieldName())) { quantity = item.getString(); } else if ("category".equals(item.getFieldName())) { category = item.getString(); } } } //File uploaded successfully System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } boolean status = ItemRepository.editItem(name, itemCode, price, quantity, category, image, id); String message; System.out.println(status); if (status) { message = "Item saved successfully"; response.sendRedirect("dashboard"); } else { message = "Item not saved !!"; request.setAttribute("message", message); request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response); } }