List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.example.webapp.filter.MultipartFilter.java
/** * Parse the given HttpServletRequest. If the request is a multipart * request, then all multipart request items will be processed, else the * request will be returned unchanged. During the processing of all * multipart request items, the name and value of each regular form field * will be added to the parameterMap of the HttpServletRequest. The name and * File object of each form file field will be added as attribute of the * given HttpServletRequest. If a FileUploadException has occurred when the * file size has exceeded the maximum file size, then the * FileUploadException will be added as attribute value instead of the * FileItem object./*from www .jav a 2 s . co m*/ * * @param request The HttpServletRequest to be checked and parsed as * multipart request. * @return The parsed HttpServletRequest. * @throws ServletException If parsing of the given HttpServletRequest * fails. */ @SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type. private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException { // Check if the request is actually a multipart/form-data request. if (!ServletFileUpload.isMultipartContent(request)) { // If not, then return the request unchanged. return request; } // Prepare the multipart request items. // I'd rather call the "FileItem" class "MultipartItem" instead or so. // What a stupid name ;) List<FileItem> multipartItems = null; try { // Parse the multipart request items. multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); // Note: we could use ServletFileUpload#setFileSizeMax() here, but // that would throw a // FileUploadException immediately without processing the other // fields. So we're // checking the file size only if the items are already parsed. See // processFileField(). } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request: " + e.getMessage()); } // Prepare the request parameter map. Map<String, String[]> parameterMap = new HashMap<String, String[]>(); // Loop through multipart request items. for (FileItem multipartItem : multipartItems) { if (multipartItem.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). processFormField(multipartItem, parameterMap); } else { // Process form file field (input type="file"). processFileField(multipartItem, request); } } // Wrap the request with the parameter map which we just created and // return it. return wrapRequest(request, parameterMap); }
From source file:ManageDatasetFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . 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("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //get the dataset files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String datasetid = request.getParameter("datasetid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getDatasetFiles")) { //getting dataset files //first get the filenames in the directory. //I will get the list of files in this directory and send it String datasetPath = getServletContext().getRealPath("/datasets/" + datasetid); System.out.println(datasetid); File root = new File(datasetPath); File[] list = root.listFiles(); ArrayList<String> fileItemList = new ArrayList<String>(); if (list == null) { System.out.println("List is null"); return; } for (File f : list) { if (f.isDirectory()) { ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName()); for (int i = 0; i < dirItems.size(); i++) { fileItemList.add(dirItems.get(i)); } } else { System.out.println(f.getName()); fileItemList.add(f.getName()); } } System.out.println("**** Printing the fileItems now **** "); String outputStr = ""; for (int i = 0; i < fileItemList.size(); i++) { outputStr += fileItemList.get(i); } if (outputStr.length() > 1) { out.println(outputStr); } } else if (command.equalsIgnoreCase("addDatasetFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/datasets/" + datasetid); File studyFolder = new File(studyFolderPath); //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); int cnt = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { // cnt++; String name = new File(item.getName()).getName(); //write the file to disk if (!studyFolder.exists()) { studyFolder.mkdir(); System.out.println("The Folder has been created"); } item.write(new File(studyFolder + File.separator + name)); System.out.println("File name is :: " + name); } } System.out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); System.out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); System.out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteDatasetFiles")) { //get the array of files and delete thems String[] mpk; //get the array of file-names mpk = request.getParameterValues("fileNames"); for (int i = 0; i < mpk.length; i++) { String filePath = getServletContext().getRealPath("/datasets/" + datasetid + "/" + mpk[i]); System.out.println(filePath); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:com.flipkart.poseidon.core.PoseidonServlet.java
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException { // If uploaded file size is more than 10KB, will be stored in disk DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = new File(FILE_UPLOAD_TMP_DIR); if (repository.exists()) { factory.setRepository(repository); }/*w w w . j ava 2 s.c o m*/ // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem // Apps also have to delete tmp file explicitly (if at all it went to disk) ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(httpRequest); } catch (FileUploadException e) { throw new IOException(e); } for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { request.setAttribute(name, new String[] { fileItem.getString() }); } else { request.setAttribute(name, fileItem); } } }
From source file:com.globalsight.everest.webapp.pagehandler.tm.management.FileUploadHelper.java
private File saveTmpFile(List<FileItem> fileItems) throws Exception { File file = null;//from w w w .j a va2 s . c o m // Create a temporary file to store the contents in it for now. We might // not have additional information, such as TUV id for building the // complete file path. We will save the contents in this file for now // and finally rename it to correct file name. file = File.createTempFile("GSTMUpload", null); // Set overall request size constraint long uploadTotalSize = 0; for (FileItem item : fileItems) { if (!item.isFormField()) { uploadTotalSize += item.getSize(); } } status.setTotalSize(uploadTotalSize); for (FileItem item : fileItems) { if (!item.isFormField()) { // If it's a ZIP archive, then expand it on the fly. // Disallow archives containing multiple files; let the // rest of the import/validation code figure out if the // contents is actually TMX or not. String fileName = getFileName(item.getName()); if (fileName.toLowerCase().endsWith(".zip")) { CATEGORY.info("Encountered zipped upload " + fileName); ZipInputStream zis = new ZipInputStream(item.getInputStream()); boolean foundFile = false; for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) { if (e.isDirectory()) { continue; } if (foundFile) { throw new IllegalArgumentException( "Uploaded zip archives should only " + "contain a single file."); } foundFile = true; FileOutputStream os = new FileOutputStream(file); int expandedSize = copyData(zis, os); os.close(); // Update file name and size to reflect zip entry setFilename(getFileName(e.getName())); status.setTotalSize(expandedSize); CATEGORY.info("Saved archive entry " + e.getName() + " to tempfile " + file); } } else { item.write(file); setFilename(fileName); CATEGORY.info("Saving upload " + fileName + " to tempfile " + file); } } else { m_fields.put(item.getFieldName(), item.getString()); } } return file; }
From source file:com.recipes.controller.Recipes.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a 2s. 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"); DAO dao = new DAO(); HttpSession session = request.getSession(true); if (request.getParameter("add") != null) { response.sendRedirect("addRecipe.jsp"); } else if (request.getParameter("insert") != null) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { // fayl yoxdur mesaj return; } String title = "";//String deyiwenleri gotururuy String article = ""; String category = ""; String prepareRules = ""; String image = ""; List<String> composition = new ArrayList<>(); String cook_time = ""; String total_time = ""; String prep_time = ""; while (it.hasNext()) { // eger file varsa FileItem fileItem = it.next(); // iteratorun next metodu cagrilir boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki if (isFormField) { // eger isFormFIelddise switch (fileItem.getFieldName()) { case "title": title = fileItem.getString("UTF-8").trim(); break; case "category": category = fileItem.getString("UTF-8").trim(); break; case "article": article = fileItem.getString("UTF-8").trim(); break; case "prepareRules": prepareRules = fileItem.getString("UTF-8").trim(); break; case "image": image = fileItem.getString("UTF-8").trim(); break; case "tags": composition.add(fileItem.getString("UTF-8").trim()); break; case "prep_time": prep_time = fileItem.getString("UTF-8").trim(); break; case "cook_time": cook_time = fileItem.getString("UTF-8").trim(); break; case "total_time": total_time = fileItem.getString("UTF-8").trim(); break; } } else { if (fileItem.getFieldName().equals("image")) { if (!fileItem.getString("UTF-8").trim().equals("")) { image = fileItem.getName(); image = dao.generateCode() + image; String relativeWebPath = "photos"; String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath); File file = new File(absoluteDiskPath + "/", image); fileItem.write(file); } } } } Recipe recipe = new Recipe(); recipe.setArticle(article); recipe.setCategory(category); String comps = ""; for (String c : composition) comps += c + ","; if (comps.contains(",")) comps = comps.substring(0, comps.length() - 1); recipe.setComposition(comps); if (image.isEmpty()) { image = "defaultrecipe.jpg"; } recipe.setImage(image); recipe.setLike_count(0); recipe.setPrepared_rules(prepareRules); recipe.setTitle(title); recipe.setUser_id(Integer.parseInt(session.getAttribute("user_id").toString())); recipe.setVisible(1); recipe.setPrep_time(prep_time); recipe.setCook_time(cook_time); recipe.setTotal_time(total_time); dao.insertRecipe(recipe); response.sendRedirect("addRecipe.jsp?success="); } catch (Exception e) { e.printStackTrace(System.out); } } else if (request.getParameter("id") != null) { response.sendRedirect("recipeDetails.jsp?id=" + request.getParameter("id")); } else { response.sendRedirect("index.jsp"); } }
From source file:net.formio.upload.MultipartRequestPreprocessor.java
private void convertToMaps(List<FileItem> fileItems) { for (FileItem item : fileItems) { String cts = item.getContentType(); if (!item.isFormField()) { // not simple form field String filename = item.getName(); long size = item.getSize(); // size in bytes // some browsers are sending "files" even if none is selected? if (size == 0 && ((cts == null || cts.isEmpty()) || "application/octet-stream".equalsIgnoreCase(cts)) && (filename == null || filename.isEmpty())) continue; String fileNameLastPart = filename; if (filename != null) { Matcher m = EXTRACT_LASTPART_PATTERN.matcher(filename); if (m.matches()) { fileNameLastPart = m.group(1); }//from ww w . j a v a 2 s .c o m } String mime = cts; if (mime == null) { mime = guessContentType(filename); } RequestUploadedFile file = new RequestUploadedFile(fileNameLastPart, mime, size, item); if (fileParams.get(item.getFieldName()) != null) { addMultivaluedFile(file, item); } else { addSingleValueFile(file, item); } } else { if (regularParams.get(item.getFieldName()) != null) { addMultivaluedItem(item); } else { addSingleValueItem(item); } } } }
From source file:communicator.doMove.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; JSONObject outputObject = new JSONObject(); try { HashMap<String, String> bigItemIds = new HashMap<>(); Iterator mIterator = bigItemIds.keySet().iterator(); out = response.getWriter(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); final String moveId = UUID.randomUUID().toString(); final MovesDb movesDb = new MovesDb(); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { System.out.println("Form field" + item.getString()); bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb); mIterator = bigItemIds.keySet().iterator(); System.out.println("ITEM ID SIZE " + bigItemIds.size()); } else { //processUploadedFile(item); System.out.print("Photo Field"); String key = (String) mIterator.next(); File mFile = new File(bigItemIds.get(key)); item.write(mFile); } } new Thread() { public void run() { pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue(); moveToMailQueue.pushMoveToMailQueue(movesDb); } }.start(); outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS); outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); } catch (Exception ex) { outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE); outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:edu.fullerton.ldvservlet.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from w ww . j av a 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("This action requires a multipart form with a file attached."); } ServletSupport servletSupport; servletSupport = new ServletSupport(); servletSupport.init(request, viewerConfig, false); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); ImageTable imageTable; String viewServletPath = request.getContextPath() + "/view"; try { imageTable = new ImageTable(servletSupport.getDb()); } catch (SQLException ex) { String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " " + ex.getLocalizedMessage(); throw new ServletException(ermsg); } try { HashMap<String, String> params = new HashMap<>(); ArrayList<Integer> uploadedIds = new ArrayList<>(); Page vpage = servletSupport.getVpage(); vpage.setTitle("Image upload"); try { servletSupport.addStandardHeader(version); servletSupport.addNavBar(); } catch (WebUtilException ex) { throw new ServerException("Adding nav bar after upload", ex); } // Parse the request List<FileItem> items = upload.parseRequest(request); int cnt = items.size(); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (!value.isEmpty()) { params.put(name, value); } } } for (FileItem item : items) { if (!item.isFormField()) { int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable); if (imgId != 0) { uploadedIds.add(imgId); } } } if (!uploadedIds.isEmpty()) { showImages(vpage, uploadedIds, imageTable, viewServletPath); } servletSupport.showPage(response); } catch (FileUploadException ex) { Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.ephesoft.gxt.admin.server.DocumentTypeLearnFileServlet.java
@SuppressWarnings("unchecked") private void attachFile(HttpServletRequest req, HttpServletResponse resp) throws IOException { BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBaseFolderLocation() + File.separator + "tempLearnFile"; File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdirs(); } else {//from w ww . ja v a2 s . c om FileUtils.deleteContents(exportSerailizationFolderPath, false); exportSerailizationFolder.mkdirs(); } String learnFileName = null; String pathToLearnFile = null; String learnFileExtension = null; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { learnFileName = item.getName(); if (learnFileName != null) { learnFileName = learnFileName.substring(learnFileName.lastIndexOf(File.separator) + 1); learnFileExtension = learnFileName.substring(learnFileName.lastIndexOf(".") + 1); } pathToLearnFile = EphesoftStringUtil.concatenate(exportSerailizationFolderPath, File.separator, learnFileName); int numberOfPages = 0; File learnedFile = new File(pathToLearnFile); batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER); documentType = req.getParameter(DocumentTypeConstants.DOCUMENT_TYPE_REQ_PARAMETER); try { item.write(learnedFile); if (learnFileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) { numberOfPages = PDFUtil.getPDFPageCount(pathToLearnFile); converPDFTotiffFile(pathToLearnFile, numberOfPages); copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName); } else if (learnFileExtension.equalsIgnoreCase(FileType.TIF.getExtension()) || learnFileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) { numberOfPages = TIFFUtil.getTIFFPageCount(pathToLearnFile); if (numberOfPages != 1) { convertMultiPageTiffToSinglePageTiff(pathToLearnFile, numberOfPages); copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName); } else { copyFilesFromTempToLearnFolders(exportSerailizationFolderPath, learnFileName, FIRST_PAGE); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); } } }
From source file:datalab.upo.ladonspark.controller.uploadFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w . j a v a 2 s. com * * @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, Exception { List<objectresult> lor = new ArrayList<>(); List<objectresult> loraux = new ArrayList<>(); boolean result = false; String urlf = ""; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // req es la HttpServletRequest que recibimos del formulario. // Los items obtenidos sern cada uno de los campos del formulario, // tanto campos normales como ficheros subidos. List items = upload.parseRequest(request); // Se recorren todos los items, que son de tipo FileItem for (Object item : items) { FileItem uploaded = (FileItem) item; // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero // subido donde nos interese if (!uploaded.isFormField()) { // No es campo de formulario, guardamos el fichero en algn sitio if (!uploaded.getName().equals("")) { urlf = uploaded.getName(); File fichero = new File(this.getPath() + "src/main/webapp/algorithm/dataAlgoritm/", uploaded.getName()); uploaded.write(fichero); } else { result = true; } } else { // es un campo de formulario, podemos obtener clave y valor String key = uploaded.getFieldName(); String value = uploaded.getString(); lor.add(new objectresult(key, value)); if (value == null || value.equals("")) { result = true; } } } if (result) { request.getSession().setAttribute("error", "error"); String url = "algorithm/addalgo.jsp"; response.sendRedirect(url); } else { Algorithm a = new Algorithm(lor.get(0).getValue(), lor.get(1).getValue(), urlf); DaoAlgoritm da = new DaoAlgoritm(); da.create(a); a = da.getAlgoritm(a.getNameAlg()); DaoParameter dp = new DaoParameter(); for (int i = 3; i < lor.size(); i++) { dp.create(new Parameter(a, lor.get(i).getValue(), lor.get(i + 1).getValue())); i++; } request.getSession().setAttribute("algorithm", new DaoAlgoritm().optenerAlgoritmos()); String url = "algorithm/masteralgo.jsp"; response.sendRedirect(url); } }