List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.surevine.alfresco.audit.listeners.PerishableUploadDocumentAuditEventListener.java
@Override protected void populateSecondaryAuditItems(List<Auditable> events, HttpServletRequest request, HttpServletResponse response, JSONObject postContent) throws JSONException { // Create a ServletFileUpload instance to parse the form ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); if (ServletFileUpload.isMultipartContent(request)) { try {/*from w ww .j a v a 2 s .c o m*/ String perishableReason = null; String tags = null; for (final Object o : upload.parseRequest(request)) { FileItem item = (FileItem) o; if (item.isFormField() && "perishable".equals(item.getFieldName())) { perishableReason = item.getString(); } else if (item.isFormField() && "tags".equals(item.getFieldName())) { tags = item.getString(); } } Auditable primaryEvent = events.get(0); // If this is a site with perish reasons configured... if (_perishabilityLogic.getPerishReasons(primaryEvent.getSite()).size() > 0) { AuditItem item = new AuditItem(); setGenericAuditMetadata(item, request); // Copy any relevant fields from the primary audit event item.setNodeRef(primaryEvent.getNodeRef()); item.setVersion(primaryEvent.getVersion()); item.setSecLabel(primaryEvent.getSecLabel()); item.setSource(primaryEvent.getSource()); item.setAction(MarkPerishableAuditEventListener.ACTION); if (!StringUtils.isBlank(perishableReason)) { item.setDetails(perishableReason); } else { item.setDetails(MarkPerishableAuditEventListener.NO_PERISHABLE_MARK); } if (tags != null) { item.setTags(StringUtils.join(tags.trim().split(" "), ',')); } events.add(item); } } catch (FileUploadException e) { logger.error("Error while parsing request form", e); } } }
From source file:edu.vt.vbi.patric.portlets.CircosGenomeViewerPortlet.java
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { Map<String, Object> parameters = new LinkedHashMap<>(); int fileCount = 0; try {//from w w w .j av a 2s . co m List<FileItem> items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { parameters.put(item.getFieldName(), item.getString()); } else { if (item.getFieldName().matches("file_(\\d+)$")) { parameters.put("file_" + fileCount, item); fileCount++; } } } } catch (FileUploadException e) { LOGGER.error(e.getMessage(), e); } LOGGER.debug(parameters.toString()); // Generate Circo Image CircosData circosData = new CircosData(request); Circos circosConf = circosGenerator.createCircosImage(circosData, parameters); if (circosConf != null) { String baseUrl = "https://" + request.getServerName(); String redirectUrl = baseUrl + "/portal/portal/patric/CircosGenomeViewer/CircosGenomeViewerWindow?action=b&cacheability=PAGE&imageId=" + circosConf.getUuid() + "&trackList=" + StringUtils.join(circosConf.getTrackList(), ","); LOGGER.trace("redirect: {}", redirectUrl); response.sendRedirect(redirectUrl); } }
From source file:com.controller.ChangeImageServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/* w w w . j a v a 2s . com*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // process only if it is multipart content String path = ""; if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); path = UPLOAD_DIRECTORY + File.separator + name; } } } catch (Exception e) { e.printStackTrace(); } } response.setContentType("text/plain"); response.getWriter().write(path); }
From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotService.java
/** * Return the Field (param) with the given name as a {@link FileItem} * /* w w w . j ava2 s . c o m*/ * @param items * @param name * @return */ private String getFieldValue(List<FileItem> items, String name) { for (FileItem item : items) { if (item.isFormField() && name.equals(item.getFieldName())) { return item.getString(); } } return null; }
From source file:eu.wisebed.wiseui.server.rpc.ImageUploadServiceImpl.java
/** * Override executeAction to save the received files in a custom place * and delete these items from session//from w w w. j a v a 2 s . c om */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { // Save a temporary file in the default system temp directory File uploadedFile = File.createTempFile("upload-", ".bin"); // write item to a file item.write(uploadedFile); // open and read content from file stream FileInputStream in = new FileInputStream(uploadedFile); byte fileContent[] = new byte[(int) uploadedFile.length()]; in.read(fileContent); // store content in persistance BinaryImage image = new BinaryImage(); image.setFileName(item.getName()); image.setFileSize(item.getSize()); image.setContent(fileContent); image.setContentType(item.getContentType()); LOGGER.info("Storing image: [Filename-> " + item.getName() + " ]"); persistenceService.storeBinaryImage(image); // Compose an xml message with the full file information // which can be parsed in client side response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "-type>\n"; } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // set the count of files response += "<file-count>" + cont + "</file-count>\n"; // Send information of the received files to the client return "<response>\n" + response + "</response>\n"; }
From source file:AES.Controllers.FileController.java
@RequestMapping(value = "/upload", method = RequestMethod.GET) public void upload(HttpServletResponse response, HttpServletRequest request, @RequestParam Map<String, String> requestParams) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Hello<br/>"); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("You are not trying to upload<br/>"); return;//from ww w . j a v a 2s . c o m } out.println("You are trying to upload<br/>"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { out.println("No fields found"); return; } out.println("<table border=\"1\">"); while (it.hasNext()) { out.println("<tr>"); FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString()); out.println("</td>"); } else { out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName() + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): " + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString()); out.println("</td>"); String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\"; //System.out.println(request.getSession().getServletContext().getRealPath("")); File f = new File(path + fileItem.getName()); if (!f.exists()) f.createNewFile(); fileItem.write(f); } out.println("</tr>"); } out.println("</table>"); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception ex) { Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:controller.uploadPergunta9ArquivoAjuste.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www .j av 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 { String idLocal = (String) request.getParameter("idLocal"); String expressaoModelo = (String) request.getParameter("expressaoModelo"); String nomeAutorModelo = (String) request.getParameter("nomeAutorModelo"); String name = ""; //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); // item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); item.write(new File(AbsolutePath + File.separator + name)); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } expressaoModelo = expressaoModelo.replace("+", "%2B"); RequestDispatcher view = getServletContext() .getRequestDispatcher("/novoLocalPergunta9?id=" + idLocal + "&nomeArquivoAjuste=" + name + "&expressaoModelo=" + expressaoModelo + "&nomeAutorModelo=" + nomeAutorModelo); view.forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response); }
From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotService.java
/** * Return the file which is uploaded as a {@link FileItem} * /*from w w w . j av a2s. co m*/ * @param items * @return */ private FileItem getUploadedFileItem(List<FileItem> items) { for (FileItem item : items) { if (!item.isFormField()) { return item; } } return null; }
From source file:eg.nileu.cis.nilestore.webapp.servlets.UploadServletRequest.java
/** * Init_ajax upload.// w ww . j av a2 s. co m * * @throws Exception * the exception */ @SuppressWarnings("unchecked") private void init_ajaxUpload() throws Exception { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File f = File.createTempFile("upfile", ".tmp"); f.deleteOnExit(); item.write(f); fileName = item.getName(); if (fileName.contains(File.separator)) { fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); } filePath = f.getAbsolutePath(); isFileFound = true; // Here we handle only one file at once break; } else { if (item.getFieldName().equals(DEST_FIELD_NAME)) { dest = Integer.valueOf(item.getString()); } } } String t = getParameter("t"); if (t != null) { returnType = t; } }
From source file:controller.uploadPergunta8.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww .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 { String idLocal = (String) request.getParameter("idLocal"); String idModelo = (String) request.getParameter("idModelo"); String equacaoAjustada = (String) request.getParameter("equacaoAjustada"); String idEquacaoAjustada = (String) request.getParameter("idEquacaoAjustada"); String name = ""; //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); // item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); item.write(new File(AbsolutePath + File.separator + name)); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } equacaoAjustada = equacaoAjustada.replace("+", "%2B"); RequestDispatcher view = getServletContext().getRequestDispatcher( "/novoLocalPergunta8?id=" + idLocal + "&nomeArquivo=" + name + "&idModelo=" + idModelo + "&equacaoAjustada=" + equacaoAjustada + "&idEquacaoAjustada=" + idEquacaoAjustada); view.forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response); }