List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.controller.UploadLogo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a 2s. 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(); 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:com.silverpeas.importExportPeas.servlets.ImportExportRequestRouter.java
/** * This method has to be implemented by the component request rooter it has to compute a * destination page//from w w w. j av a 2 s . co m * * @param function The entering request function (ex : "Main.jsp") * @param importExportSC The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/notificationUser/jsp/notificationUser.jsp?flag=user") */ @Override public String getDestination(String function, ImportExportSessionController importExportSC, HttpRequest request) { String destination = ""; try { if (function.startsWith("Main")) { destination = "/importExportPeas/jsp/welcome.jsp"; } else if ("Import".equals(function)) { File file = null; List<FileItem> items = request.getFileItems(); for (FileItem item : items) { if (!item.isFormField()) { String fileName = FileUploadUtil.getFileName(item); file = new File(FileRepositoryManager.getTemporaryPath(null, null) + fileName); FileUploadUtil.saveToFile(file, item); } } ImportReport importReport = importExportSC.processImport(file.getAbsolutePath(), (ResourcesWrapper) request.getAttribute("resources")); request.setAttribute("importReport", importReport); destination = "/importExportPeas/jsp/viewSPExchange.jsp"; } else if ("SelectExportMode".equals(function)) { List<WAAttributeValuePair> itemPKs = (List<WAAttributeValuePair>) request .getAttribute("selectedResultsWa"); NodePK rootPK = (NodePK) request.getAttribute("RootPK"); importExportSC.saveItems(itemPKs, rootPK); destination = "/importExportPeas/jsp/selectExportMode.jsp"; } else if ("ExportSavedItems".equals(function)) { String mode = request.getParameter("ExportMode"); importExportSC.processExportOfSavedItems(mode); destination = "/importExportPeas/jsp/pingExport.jsp"; } else if ("ExportItems".equals(function)) { @SuppressWarnings("unchecked") List<WAAttributeValuePair> itemPKs = (List<WAAttributeValuePair>) request .getAttribute("selectedResultsWa"); NodePK rootPK = (NodePK) request.getAttribute("RootPK"); if (itemPKs != null && !itemPKs.isEmpty()) { importExportSC.processExport(itemPKs, rootPK); destination = "/importExportPeas/jsp/pingExport.jsp"; } else { destination = "/importExportPeas/jsp/nothingToExport.jsp"; } } else if ("ExportItemsPing".equals(function)) { if (importExportSC.isExportInProgress()) { destination = "/importExportPeas/jsp/pingExport.jsp"; } else { ExportReport report = importExportSC.getExportReport(); request.setAttribute("ExportReport", report); destination = "/importExportPeas/jsp/downloadZip.jsp"; } } else if ("ExportPDF".equals(function)) { List<WAAttributeValuePair> itemPKs = (List<WAAttributeValuePair>) request .getAttribute("selectedResultsWa"); String rootId = (String) request.getAttribute("RootId"); if (itemPKs != null && !itemPKs.isEmpty()) { ExportPDFReport report = importExportSC.processExportPDF(itemPKs); if (report != null) { request.setAttribute("ExportPDFReport", report); destination = "/importExportPeas/jsp/downloadPdf.jsp"; } else { destination = "/importExportPeas/jsp/nothingToExport.jsp"; } } else { destination = "/importExportPeas/jsp/nothingToExport.jsp"; } } else if (function.equals("KmaxExportComponent")) { @SuppressWarnings("unchecked") List<WAAttributeValuePair> itemPKs = (List<WAAttributeValuePair>) request .getAttribute("selectedResultsWa"); if (itemPKs != null && !itemPKs.isEmpty()) { ExportReport report = importExportSC.processExportKmax(importExportSC.getLanguage(), itemPKs, null, null); request.setAttribute("ExportReport", report); destination = "/importExportPeas/jsp/downloadZip.jsp"; } else { destination = "/importExportPeas/jsp/nothingToExport.jsp"; } } else if (function.equals("KmaxExportPublications")) { @SuppressWarnings("unchecked") List<WAAttributeValuePair> itemPKs = (List<WAAttributeValuePair>) request .getAttribute("selectedResultsWa"); List combination = (List) request.getAttribute("Combination"); String timeCriteria = (String) request.getAttribute("TimeCriteria"); if (itemPKs != null && !itemPKs.isEmpty()) { ExportReport report = importExportSC.processExportKmax(importExportSC.getLanguage(), itemPKs, combination, timeCriteria); request.setAttribute("ExportReport", report); destination = "/importExportPeas/jsp/downloadZip.jsp"; } else { destination = "/importExportPeas/jsp/nothingToExport.jsp"; } } else { destination = "/importExportPeas/jsp/" + function; } } catch (Exception e) { request.setAttribute("javax.servlet.jsp.jspException", e); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
From source file:com.assignment.elance.controller.FileUploadServlet.java
/** * Upon receiving file upload submission, parses the request to read upload * data and saves the file on disk./*from w w w . j a v a 2s . co m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 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 has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + SystemAttributes.UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String file = randomFileNameGenerator(); String filePath = uploadPath + File.separator + file; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); FilesManager fm = new FilesManager(); boolean send_dir = false; switch (Integer.parseInt(request.getParameter("senddir"))) { case 0: send_dir = false; break; case 1: send_dir = true; break; } fm.insert(fileName, file, Integer.parseInt(request.getParameter("jobId")), send_dir); request.setAttribute("message", "Upload has been done successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // // redirects client to message page // getServletContext().getRequestDispatcher("/message.jsp").forward( // request, response); switch (Integer.parseInt(request.getParameter("callbackpage"))) { case 0: response.sendRedirect("projectOverview.jsp?pId=" + Integer.parseInt(request.getParameter("jobId"))); break; case 1: response.sendRedirect("project.jsp?jobId=" + Integer.parseInt(request.getParameter("jobId"))); break; } }
From source file:com.eufar.emc.server.UploadFunction.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadFunction - the function started"); response.setContentType("text/html;charset=UTF-8"); response.addHeader("Cache-Control", "no-cache,no-store"); @SuppressWarnings("unused") boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from w w w. j av a 2 s . c o m*/ List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj == null) { continue; } org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) { if (item.isFormField()) { String name = item.getName(); String value = ""; if (name.compareTo("textBoxFormElement") == 0) { value = item.getString(); } else { value = item.getString(); } response.getWriter().write(name + "=" + value + "\n"); } else { byte[] fileContents = item.get(); String message = new String(fileContents); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(message); System.out.println("UploadFunction - file uploaded"); } } else { System.out.println("UploadFunction - file rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadFunction - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:business.controllers.UploadImageController.java
public void uploadImage(HttpServletRequest request, HttpServletResponse response, List formItems) throws IOException { BusinessChatHandler handler = new BusinessChatHandler(); Long imageId;/* w w w . j a v a2 s. c o m*/ try { imageId = (Long) handler.getImageId(); } catch (TException ex) { imageId = 0L; logger.error("get image id:" + ex); } String filePath = ""; String uploadPath = "../resources/" + UploadConstant.UPLOAD_DIRECTORY; // parses the request's content to extract file data Iterator iter = formItems.iterator(); String userId = ""; String fileName = ""; File storeFile = null; // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { try { fileName = new File(item.getName()).getName(); String extensionImage = ""; for (int i = fileName.length() - 1; i >= 0; i--) { if (fileName.charAt(i) == '.') { break; } else { extensionImage = fileName.charAt(i) + extensionImage; } } //tao file name moi // fileName = imageId + "." + extensionImage; // fileName = imageId + "_" + fileName; filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); // saves the file on disk item.write(storeFile); } catch (Exception ex) { logger.error("error when write image"); } } else if (item.getFieldName().equals("userId")) { userId = item.getString(); } } if (storeFile != null) { //userID_imageGen_fileNameofUser.jpg fileName = userId + "_" + imageId + "_" + fileName; filePath = uploadPath + File.separator + fileName; File newNameImage = new File(filePath); storeFile.renameTo(newNameImage); } response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html"); response.getWriter().println(filePath); }
From source file:com.esri.gpt.control.filter.MultipartWrapper.java
/** * Construct with a current HTTP servlet request. * @param request the current HTTP servlet request * @throws FileUploadException if an exception occurs during file upload *//* w ww . j av a2 s.c o m*/ public MultipartWrapper(HttpServletRequest request) throws FileUploadException { super(request); getLogger().finer("Handling multipart content."); // initialize parameters _fileParameters = new HashMap<String, FileItem>(); _formParameters = new HashMap<String, String[]>(); int nFileSizeMax = 100000000; int nSizeThreshold = 500000; String sTmpFolder = ""; // make the file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(nSizeThreshold); if (sTmpFolder.length() > 0) { File fTmpFolder = new File(sTmpFolder); factory.setRepository(fTmpFolder); } // make the file upload object ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setFileItemFactory(factory); fileUpload.setFileSizeMax(nFileSizeMax); // parse the parameters associated with the request List items = fileUpload.parseRequest(request); String[] aValues; ArrayList<String> lValues; for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); getLogger().finer("FileItem=" + item); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); if (_formParameters.containsKey(sName)) { aValues = _formParameters.get(sName); lValues = new ArrayList<String>(Arrays.asList(aValues)); lValues.add(sValue); aValues = lValues.toArray(new String[0]); } else { aValues = new String[1]; aValues[0] = sValue; } _formParameters.put(sName, aValues); } else { _fileParameters.put(item.getFieldName(), item); request.setAttribute(item.getFieldName(), item); } } }
From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java
/** * Handles the HTTP//from www . j a va 2 s. c o m * <code>POST</code> method. * * @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 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); String assignmentid = ""; String filename = ""; while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println(fileItem); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(); if (name.equalsIgnoreCase("assignmentid")) { assignmentid = value; } System.out.println("Assignment id==" + assignmentid); } if (fileItem.getName() != null) { File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); filename = fileItem.getName(); } } assignmentFoldetService = new AssignmentFolderService(); assignmentFoldetService.updateAssignmentFolder(username, assignmentid, filename); } catch (FileUploadException e) { System.out.println("Exception in file upload" + e); } catch (Exception ex) { Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex); } processRequest(request, response); }
From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java
@SuppressWarnings("rawtypes") public <T> T convert(Request restRequest, Class<T> paramClass) { //multipart/form-data??requestString/inputStream T pojo;/*from w w w . j av a2s. com*/ try { pojo = paramClass.newInstance(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(Magic.MultiPartFileSizeMax); List items = upload.parseRequest(restRequest.getRawRequest()); Iterator iter = items.iterator();//upload.getItemIterator(restRequest.getRawRequest()); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); logger.debug(item.toString()); if (item.isFormField()) { processFormField(item, pojo); } else { processUploadedFile(item, pojo); } } return pojo; } catch (InstantiationException e) { logger.error("can't instantiate a pojo of {}, please check the Pojo", paramClass); throw new RuntimeException(e); } catch (IllegalAccessException e) { logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo", paramClass); throw new RuntimeException(e); } catch (FileUploadException e) { logger.error("fileupload error.", paramClass); throw new RuntimeException(e); } }
From source file:com.xclinical.mdr.server.DocumentServlet.java
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { try {/*ww w .j a v a 2s .c om*/ if (ServletFileUpload.isMultipartContent(req)) { log.debug("detected multipart content"); final FileInfo info = new FileInfo(); ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> items = fileUpload.parseRequest(req); String session = null; for (Iterator<FileItem> i = items.iterator(); i.hasNext();) { log.debug("detected form field"); FileItem item = (FileItem) i.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName != null) { log.debug("{0}={1}", fieldName, fieldValue); } else { log.severe("fieldName may not be null"); } if ("session".equals(fieldName)) { session = fieldValue; } } else { log.debug("detected content"); info.contentName = item.getName(); info.contentName = new File(info.contentName).getName(); info.contentType = item.getContentType(); info.content = item.get(); log.debug("{0} bytes", info.content.length); } } if (info.content == null) throw new IllegalArgumentException("there is no content"); if (info.contentType == null) throw new IllegalArgumentException("There is no content type"); if (info.contentName == null) throw new IllegalArgumentException("There is no content name"); Session.runInSession(session, new Callable<Void>() { @Override public Void call() throws Exception { Document document = Document.create(info.contentName, info.contentType, info.content); log.info("Created document " + document.getId()); ReferenceDocument referenceDocument = saveFile(req, document); JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument)); return null; } }); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } catch (FileUploadException e) { log.severe(e); throw new ServletException(e); } catch (Exception e) { log.severe(e); throw new ServletException(e); } }
From source file:com.mockey.ui.UploadConfigurationServlet.java
/** * /*from w ww.j a v a 2 s .c o m*/ * * @param req * basic request * @param resp * basic resp * @throws ServletException * basic * @throws IOException * basic */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = null; String definitionsAsString = null; String taglistValue = ""; // *********************************** // STEP #1 - READ DATA // *********************************** if (req.getParameter("viaUrl") != null) { url = req.getParameter("url"); taglistValue = req.getParameter("taglist"); try { InputStream fstream = new URL(url).openStream(); if (fstream != null) { BufferedReader br = new BufferedReader( new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8))); StringBuffer inputString = new StringBuffer(); // Read File Line By Line String strLine = null; // READ FIRST while ((strLine = br.readLine()) != null) { // Print the content on the console inputString.append(new String(strLine.getBytes(HTTP.UTF_8))); } definitionsAsString = inputString.toString(); } } catch (Exception e) { logger.error("Unable to reach url: " + url, e); Util.saveErrorMessage("Unable to reach url: " + url, req); } } else { byte[] data = null; try { // STEP 1. GATHER UPLOADED ITEMS // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Parse the request List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { data = item.get(); } else { String name = item.getFieldName(); if ("taglist".equals(name)) { taglistValue = item.getString(); } } } if (data != null && data.length > 0) { definitionsAsString = new String(data); } } catch (Exception e) { logger.error("Unable to read or parse file: ", e); Util.saveErrorMessage("Unable to upload or parse file.", req); } } // *********************************** // STEP #2 - PERSIST DATA // *********************************** try { if (definitionsAsString != null) { MockeyXmlFileManager configurationReader = new MockeyXmlFileManager(); ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString, taglistValue); Util.saveSuccessMessage("Service definitions uploaded.", req); req.setAttribute("conflicts", results.getConflictMsgs()); req.setAttribute("additions", results.getAdditionMessages()); } else { Util.saveErrorMessage("Unable to upload or parse empty file.", req); } } catch (Exception e) { Util.saveErrorMessage("Unable to upload or parse file.", req); } RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp"); dispatch.forward(req, resp); }