List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:controladoresAdministrador.ControladorCargarInicial.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w .j a va 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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); DiskFileItemFactory ff = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(ff); List items = null; File archivo = null; try { items = sfu.parseRequest(request); } catch (FileUploadException ex) { out.print(ex.getMessage()); } String nombre = ""; FileItem item = null; for (int i = 0; i < items.size(); i++) { item = (FileItem) items.get(i); if (!item.isFormField()) { nombre = item.getName(); archivo = new File(this.getServletContext().getRealPath("/archivos/") + "/" + item.getName()); try { item.write(archivo); } catch (Exception ex) { out.print(ex.getMessage()); } } } CargaInicial carga = new CargaInicial(); String ubicacion = archivo.toString(); int cargado = carga.cargar(ubicacion); if (cargado == 1) { response.sendRedirect( "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se encontro el archivo!</strong> Por favor intentelo de nuevo.&tipoAlert=warning"); } else { response.sendRedirect( "pages/indexadmin.jsp?msg=<strong>Carga inicial exitosa! <i class='glyphicon glyphicon-ok'></i></strong>&tipoAlert=success"); } }
From source file:emsa.webcoc.cleanup.servlet.UploadServet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .ja v a2 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 { isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>XML file clean up</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); //Maximum size that will be stored into memory factory.setSizeThreshold(MAXMEMSIZE); //Path to save file if its size is bigger than MAXMEMSIZE factory.setRepository(new File(REPOSITORY)); ServletFileUpload upload = new ServletFileUpload(factory); out.println("<html>"); out.println("<head>"); out.println("<title>XML file clean up</title>"); out.println("</head>"); out.println("<body>"); try { List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> t = fileItems.iterator(); while (t.hasNext()) { FileItem f = t.next(); if (!f.isFormField()) { if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name String location = (String) this.getServletContext().getAttribute("newFileLocation"); CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location); if (clean.cleanDocument(f.getInputStream()) == 0) { out.println("<h3>" + f.getName() + " was clean</h3>"); out.println(clean.printHTMLStatistics()); out.println("<br /><form action='download?filename=" + uniqueFileName + "' method='post'><input type='submit' value='Download'/></form></body></html>"); } else { out.println("<h3>" + clean.getErrorMessage() + "</h3>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); } } else { out.println("<h3>The file " + f.getName() + " is not an xml file</h3>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType()); } } } File repository = factory.getRepository(); cleanTmpFiles(repository); } catch (IOException | FileUploadException e) { out.println("<h3>Something went wrong</h3></br>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); } }
From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w . j av 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 { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = response.getWriter(); HttpSession aSession = request.getSession(); try { Person pers = (Person) aSession.getAttribute("person"); String primaryKey = pers.getAccount().getEmail(); PersonManager aPerson = PersonManager.getInstance(); Person person = aPerson.getStudent(primaryKey); ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance(); out = response.getWriter(); String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula()); File subfolderFile = new File(studentSubfolderPath); if (!subfolderFile.exists()) { subfolderFile.mkdir(); } isMultipart = ServletFileUpload.isMultipartContent(request); String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String CVPath = "", ATPath = ""; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (fieldName.equals("cv")) { fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf"); CVPath = fileToStore.getAbsolutePath(); } else if (fieldName.equals("doc")) { fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf"); ATPath = fileToStore.getAbsolutePath(); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); } } if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) { message.setMessage("status", 1); } else { message.setMessage("status", 0); } aSession.setAttribute("message", message); response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp"); //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp"); //dispatcher.forward(request,response); } catch (Exception ex) { Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex); message.setMessage("status", -1); aSession.setAttribute("message", message); } finally { out.close(); } }
From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // show add version page dispatch("addversion.jsp", "Add new version. The Blend.", request, response); }//w ww . j av a2 s. co m Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String docId = null; boolean major = true; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_DOC_ID.equalsIgnoreCase(name)) { docId = item.getString(); } else if (PARAM_MAJOR.equalsIgnoreCase(name)) { major = Boolean.parseBoolean(item.getString()); } } else { properties.put(PropertyIds.NAME, item.getName()); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!", null); } try { // find the document Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document"); // check out document and get Private Working Copy Document pwc = null; try { // check out ObjectId pwcId = doc.checkOut(); // the PWC must be a document object pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT); } catch (CmisBaseException cbe) { throw new TheBlendException("Checkout failed!", cbe); } // prepare the content stream ContentStream contentStream = null; try { contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // create new version try { newId = pwc.checkIn(major, properties, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create new version: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:com.mylop.servlet.TimelineServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w . j ava 2 s . co 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 { response.setContentType("application/json"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); HttpSession session = request.getSession(); String userid = (String) session.getAttribute("userid"); String status = "aaa"; String urlTimelineImage = ""; String title = ""; String subtitle = ""; String content = ""; Date date = new Date(Calendar.getInstance().getTimeInMillis()); TimelineModel tm = new TimelineModel(); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String contentType = item.getContentType(); String fileName = UPLOAD_DIRECTORY + File.separator + userid + "_" + (tm.getLastIndex() + 1); File file = new File(fileName); item.write(file); urlTimelineImage = "http://mylop.tk:8080/Timeline/" + file.getName(); } else { String fieldName = item.getFieldName(); if (fieldName.equals("title")) { title = item.getString(); } if (fieldName.equals("subtitle")) { subtitle = item.getString(); } if (fieldName.equals("content")) { content = item.getString(); } if (fieldName.equals("date")) { Long dateLong = Long.parseLong(item.getString()); date = new Date(dateLong); } } } tm.addTimeline(userid, title, subtitle, date, content, urlTimelineImage); } catch (Exception e) { e.printStackTrace(); } } String json = "{\"message\": \"success\"}"; response.getWriter().write(json); }
From source file:com.ikon.servlet.admin.CheckTextExtractionServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); updateSessionManager(request);/*w ww . j a v a 2s . c o m*/ InputStream is = null; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String docUuid = null; String repoPath = null; String text = null; String mimeType = null; String extractor = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("docUuid")) { docUuid = item.getString("UTF-8"); } else if (item.getFieldName().equals("repoPath")) { repoPath = item.getString("UTF-8"); } } else { is = item.getInputStream(); String name = FilenameUtils.getName(item.getName()); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); if (!name.isEmpty() && item.getSize() > 0) { docUuid = null; repoPath = null; } else if (docUuid.isEmpty() && repoPath.isEmpty()) { mimeType = null; } } } if (docUuid != null && !docUuid.isEmpty()) { repoPath = OKMRepository.getInstance().getNodePath(null, docUuid); } if (repoPath != null && !repoPath.isEmpty()) { String name = PathUtils.getName(repoPath); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); is = OKMDocument.getInstance().getContent(null, repoPath, false); } long begin = System.currentTimeMillis(); if (is != null) { if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) { TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType); if (extClass != null) { extractor = extClass.getClass().getCanonicalName(); text = RegisteredExtractors.getText(mimeType, null, is); } else { extractor = "Undefined text extractor"; } } } ServletContext sc = getServletContext(); sc.setAttribute("docUuid", docUuid); sc.setAttribute("repoPath", repoPath); sc.setAttribute("text", text); sc.setAttribute("time", System.currentTimeMillis() - begin); sc.setAttribute("mimeType", mimeType); sc.setAttribute("extractor", extractor); sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response); } } catch (DatabaseException e) { sendErrorRedirect(request, response, e); } catch (FileUploadException e) { sendErrorRedirect(request, response, e); } catch (PathNotFoundException e) { sendErrorRedirect(request, response, e); } catch (AccessDeniedException e) { sendErrorRedirect(request, response, e); } catch (RepositoryException e) { sendErrorRedirect(request, response, e); } finally { IOUtils.closeQuietly(is); } }
From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java
public MultipartServletRequest(HttpServletRequest request) throws FileUploadException { super(request); // if(!"POST".equals(request.getMethod())){ // return; // }/*from ww w . j a v a2s .c o m*/ CkeditorConfig config = CkeditorConfigurationHolder.config(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints if (config.fileupload().sizeThreshold() != null) { factory.setSizeThreshold(config.fileupload().sizeThreshold()); } if (config.fileupload().repository() != null) { factory.setRepository(config.fileupload().repository()); } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint if (config.fileupload().sizeMax() != null) { upload.setSizeMax(config.fileupload().sizeMax()); } if (config.fileupload().fileSizeMax() != null) { upload.setFileSizeMax(config.fileupload().fileSizeMax()); } // Copy params from query string Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); String paramValues[] = request.getParameterValues(paramName); if (paramValues != null) { this.paramMap.put(paramName, Literal.list(paramValues)); } } @SuppressWarnings("unchecked") List<FileItem> itemList = upload.parseRequest(request); for (FileItem item : itemList) { String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> values = paramMap.get(fieldName); if (values == null) { paramMap.put(fieldName, Literal.list(item.getString())); } else { values.add(item.getString()); } } else { fileItemMap.put(fieldName, item); fileItems.add(item); } } }
From source file:com.pdfhow.diff.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request// w w w .java 2s . c o m * 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 IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JSONArray json = new JSONArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName()); item.write(file); JSONObject jsono = new JSONObject(); jsono.put("name", item.getName()); jsono.put("size", item.getSize()); jsono.put("url", "UploadServlet?getfile=" + item.getName()); jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName()); jsono.put("delete_url", "UploadServlet?delfile=" + item.getName()); jsono.put("delete_type", "GET"); json.put(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:UploadImage.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "patzelt"; String password = "Chocolate1"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int photo_id; try {//from w w w.j a v a2 s . co m // Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } long size = item.getSize(); // Get the image stream InputStream instream = item.getInputStream(); // Connect to the database and create a statement Connection conn = getConnected(drivername, dbstring, username, password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); // good rset1.next(); photo_id = rset1.getInt(1); /** // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty // blob stmt.execute("INSERT INTO pictures (photo_id, pic_des, pic) VALUES(" + photo_id + ",'test',empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pictures WHERE photo_id = " + photo_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet) rset).getBLOB(3); **/ stmt.execute("INSERT INTO pictures VALUES(" + photo_id + ",'test',empty_blob())"); PreparedStatement stmt1 = conn .prepareStatement("UPDATE pictures SET pic = ? WHERE photo_id = + " + photo_id); stmt1.setBinaryStream(1, instream); stmt1.executeUpdate(); /** // Write the image to the blob object OutputStream outstream = myblob.setBinaryStream(size); //int bufferSize = myblob.getBufferSize(); //byte[] buffer = new byte[bufferSize]; //int length = -1; //while ((length = instream.read(buffer)) != -1) //outstream.write(buffer, 0, length); outstream.write(pic); instream.close(); outstream.close(); //String update = "UPDATE pictures SET pic = " + myblob + " WHERE photo_id = " + photo_id; //stmt.execute(update); **/ response_message = "YAHHOOOOOO"; conn.close(); } catch (Exception ex) { // System.out.println( ex.getMessage()); response_message = ex.getMessage(); } // Output response to the client response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + "</H1>\n" + "</BODY></HTML>"); }
From source file:com.fdt.sdl.admin.ui.action.UploadAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!SecurityUtil.isAdminUser(request)) return (mapping.findForward("welcome")); ActionMessages messages = new ActionMessages(); ActionMessages errors = new ActionMessages(); if (FileUpload.isMultipartContent(request)) { try {/* w w w. jav a2 s .c om*/ //read old dataset values ServerConfiguration sc = ServerConfiguration.getServerConfiguration(); ArrayList<DatasetConfiguration> old_dcs = ServerConfiguration.getDatasetConfigurations(); Map<String, Long> oldModifiedTimes = new HashMap<String, Long>(old_dcs.size()); for (DatasetConfiguration old_dc : old_dcs) { oldModifiedTimes.put(old_dc.getName(), old_dc.getConfigFile().lastModified()); } DiskFileUpload upload = new DiskFileUpload(); upload.setSizeMax(10 * 1024 * 1024); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { String fileName = (new File(item.getName())).getName(); if (fileName.endsWith(".zip")) { try { extractZip(item.getInputStream()); } catch (Exception ee) { logger.error("exception for zip:" + ee); ee.printStackTrace(); } } } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("action.uploadFiles.success")); saveMessages(request, messages); //merge old values into the new data set if (sc.getIsMergingOldDatasetValues()) { ArrayList<DatasetConfiguration> new_dcs = ServerConfiguration.getDatasetConfigurations(); for (DatasetConfiguration new_dc : new_dcs) { if (oldModifiedTimes.get(new_dc.getName()) != null && new_dc.getConfigFile().lastModified() > oldModifiedTimes.get(new_dc.getName())) { for (DatasetConfiguration old_dc : old_dcs) { if (new_dc.getName() == old_dc.getName()) { new_dc.merge(old_dc); new_dc.save(); break; } } } } } if (sc.getAllowedLicenseLevel() > 0) { //reload from the disk ArrayList<DatasetConfiguration> dcs = ServerConfiguration.getDatasetConfigurations(); for (DatasetConfiguration dc : dcs) { try { SchedulerTool.scheduleIndexingJob(dc); } catch (Throwable t) { logger.info("Failed to schedule for " + dc.getName() + ": " + t.toString()); } } } return mapping.findForward("continue"); } catch (Exception e) { errors.add("error", new ActionMessage("action.uploadFiles.error")); saveErrors(request, errors); return mapping.findForward("continue"); } } else { // from other page // } return mapping.findForward("continue"); }