List of usage examples for org.apache.commons.fileupload DefaultFileItemFactory DefaultFileItemFactory
public DefaultFileItemFactory()
From source file:net.ontopia.topicmaps.classify.ClassifyUtils.java
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) { // Handle file upload String contentType = request.getHeader("content-type"); // out.write("CT: " + contentType + " " + tm + " " + id); if (contentType != null && contentType.startsWith("multipart/form-data")) { try {//from w w w. j a v a 2 s. com FileUpload upload = new FileUpload(new DefaultFileItemFactory()); for (FileItem item : upload.parseRequest(request)) { if (item.getSize() > 0) { // ISSUE: could make use of content type if known byte[] content = item.get(); ClassifiableContent cc = new ClassifiableContent(); String name = item.getName(); if (name != null) cc.setIdentifier("fileupload:name:" + name); else cc.setIdentifier("fileupload:field:" + item.getFieldName()); cc.setContent(content); return cc; } } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } return null; }
From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object.// w ww . j av a 2s . c o m * @since 2.0 */ public static Parameters decodeParameters(HttpServletRequest request, String charenc) throws ServletException, IOException { String ctype = request.getHeader("content-type"); log.debug("Content-type: " + ctype); Parameters params = new Parameters(); if (ctype != null && ctype.startsWith("multipart/form-data")) { // special file upload request, so use FileUpload to decode log.debug("Decoding with FileUpload; charenc=" + charenc); try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); Iterator iterator = upload.parseRequest(request).iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); log.debug("Reading: " + item); if (item.isFormField()) { if (charenc != null) params.addParameter(item.getFieldName(), item.getString(charenc)); else params.addParameter(item.getFieldName(), item.getString()); } else params.addParameter(item.getFieldName(), new FileParameter(item)); } } catch (FileUploadException e) { throw new ServletException(e); } } else { // ordinary web request, so retrieve info and stuff into Parameters object log.debug("Normal parameter decode, charenc=" + charenc); if (charenc != null) request.setCharacterEncoding(charenc); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String param = (String) enumeration.nextElement(); params.addParameter(param, request.getParameterValues(param)); } } return params; }
From source file:com.slamd.admin.RequestInfo.java
/** * Creates a new set of request state information using the provided request * and response.//from w w w . j a v a2 s . c o m * * @param request Information about the HTTP request issued by the client. * @param response Information about the HTTP response that will be returned * to the client. */ public RequestInfo(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; generateHTML = true; debugInfo = new StringBuilder(); htmlBody = new StringBuilder(); infoMessage = new StringBuilder(); if (request != null) { servletBaseURI = request.getRequestURI(); userIdentifier = request.getRemoteUser(); if (FileUpload.isMultipartContent(request)) { try { FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory()); multipartFieldList = fileUpload.parseRequest(request); Iterator iterator = multipartFieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String name = fileItem.getFieldName(); if (name.equals(Constants.SERVLET_PARAM_SECTION)) { section = new String(fileItem.get()); } else if (name.equals(Constants.SERVLET_PARAM_SUBSECTION)) { subsection = new String(fileItem.get()); } } } catch (FileUploadException fue) { fue.printStackTrace(); } } else { section = request.getParameter(Constants.SERVLET_PARAM_SECTION); subsection = request.getParameter(Constants.SERVLET_PARAM_SUBSECTION); } } if (section == null) { section = ""; } if (subsection == null) { subsection = ""; } }
From source file:com.globalsight.everest.webapp.pagehandler.tasks.TaskDetailHandler.java
private void dtpUpload(HttpServletRequest p_request) throws EnvoyServletException { String uploadFileName = this.getFullTargetFilePath(p_request); try {// w ww . jav a 2 s . c o m DefaultFileItemFactory factory = new DefaultFileItemFactory(); // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(factory); List items = upload.parseRequest(p_request); Iterator iter = items.iterator(); if (iter.hasNext()) { FileItem item = (FileItem) iter.next(); File uploadDir = new File(this.getTargetFilePath(p_request)); if (!uploadDir.isDirectory()) { uploadDir.mkdir(); } File uploadFile = new File(uploadFileName); item.write(uploadFile); } } catch (FileUploadException e) { throw new EnvoyServletException(e); } catch (Exception e) { throw new EnvoyServletException(e); } }
From source file:com.slamd.admin.AdminServlet.java
/** * Handles the work of actually accepting an uploaded file and storing it in * the configuration directory./* w w w . ja v a 2 s . c o m*/ * * @param requestInfo The state information for this request. */ static void handleFileUpload(RequestInfo requestInfo) { logMessage(requestInfo, "In handleFileUpload()"); if (!requestInfo.mayManageFolders) { logMessage(requestInfo, "No mayManageFolders permission granted"); generateAccessDeniedBody(requestInfo, "You do not have permission to " + "upload files into job folders."); return; } StringBuilder infoMessage = requestInfo.infoMessage; FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory()); fileUpload.setSizeMax(maxUploadSize); boolean inOptimizing = false; String folderName = null; try { String fileName = null; String fileType = null; String fileDesc = null; int fileSize = -1; byte[] fileData = null; Iterator iterator = requestInfo.multipartFieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String fieldName = fileItem.getFieldName(); if (fieldName.equals(Constants.SERVLET_PARAM_FILE_DESCRIPTION)) { fileDesc = new String(fileItem.get()); } else if (fieldName.equals(Constants.SERVLET_PARAM_JOB_FOLDER)) { folderName = new String(fileItem.get()); } else if (fieldName.equals(Constants.SERVLET_PARAM_UPLOAD_FILE)) { fileData = fileItem.get(); fileSize = fileData.length; fileType = fileItem.getContentType(); fileName = fileItem.getName(); } else if (fieldName.equals(Constants.SERVLET_PARAM_IN_OPTIMIZING)) { String optStr = new String(fileItem.get()); inOptimizing = optStr.equalsIgnoreCase("true"); } } if (fileName == null) { infoMessage.append( "Unable to process file upload: did not receive " + "any actual file data.<BR>" + EOL); if (inOptimizing) { handleViewOptimizing(requestInfo, true, folderName); } else { handleViewJob(requestInfo, Constants.SERVLET_SECTION_JOB_VIEW_COMPLETED, folderName, null); } return; } UploadedFile file = new UploadedFile(fileName, fileType, fileSize, fileDesc, fileData); configDB.writeUploadedFile(file, folderName); infoMessage.append("Successfully uploaded file \"" + fileName + "\"<BR>" + EOL); } catch (Exception e) { infoMessage.append("Unable to process file upload: " + e + "<BR>" + EOL); } if (inOptimizing) { handleViewOptimizing(requestInfo, true, folderName); } else { handleViewJob(requestInfo, Constants.SERVLET_SECTION_JOB_VIEW_COMPLETED, folderName, null); } }
From source file:org.apache.jackrabbit.demo.blog.servlet.BlogAddControllerServlet.java
/** * This methods handles POST requests and adds the blog entries according to the parameters in the * request. Request must be multi-part encoded. *///w ww . j a va 2 s .com protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List parameters = null; String title = null; String content = null; FileItem image = null; FileItem video = null; // Check whether the request is multipart encoded if (ServletFileUpload.isMultipartContent(request)) { DefaultFileItemFactory fileItemFactory = new DefaultFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); try { // Parse the request and get the paramter set parameters = fileUpload.parseRequest(request); Iterator paramIter = parameters.iterator(); // Resolve the parameter set while (paramIter.hasNext()) { FileItem item = (FileItem) paramIter.next(); if (item.getFieldName().equalsIgnoreCase("title")) { title = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("image")) { image = item; } else if (item.getFieldName().equalsIgnoreCase("video")) { video = item; } } } catch (FileUploadException e) { throw new ServletException("Error occured in processing the multipart request", e); } } else { throw new ServletException("Request is not a multi-part encoded request"); } try { //log in to the repository and aquire a session Session session = repository.login(new SimpleCredentials("username", "password".toCharArray())); String username = (String) request.getSession().getAttribute("username"); // Only logged in users are allowed to create blog entries if (username == null) { //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Authentication Required"); request.setAttribute("msgBody", "Only logged in users are allowed to add blog entries."); request.setAttribute("urlText", "go back to login page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/index.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } Node blogRootNode = session.getRootNode().getNode("blogRoot"); Node userNode = blogRootNode.getNode(username); // Node to hold the current year Node yearNode; // Node to hold the current month Node monthNode; // Node to hold the blog entry to be added Node blogEntryNode; // Holds the name of the blog entry node String nodeName; // createdOn property of the blog entry is set to the current time. Calendar calendar = Calendar.getInstance(); String year = calendar.get(Calendar.YEAR) + ""; String month = calendar.get(Calendar.MONTH) + ""; // check whether node exists for current year under usernode and creates a one if not exist if (userNode.hasNode(year)) { yearNode = userNode.getNode(year); } else { yearNode = userNode.addNode(year, "nt:folder"); } // check whether node exists for current month under the current year and creates a one if not exist if (yearNode.hasNode(month)) { monthNode = yearNode.getNode(month); } else { monthNode = yearNode.addNode(month, "nt:folder"); } if (monthNode.hasNode(title)) { nodeName = createUniqueName(title, monthNode); } else { nodeName = title; } // creates a blog entry under the current month blogEntryNode = monthNode.addNode(nodeName, "blog:blogEntry"); blogEntryNode.setProperty("blog:title", title); blogEntryNode.setProperty("blog:content", content); Value date = session.getValueFactory().createValue(Calendar.getInstance()); blogEntryNode.setProperty("blog:created", date); blogEntryNode.setProperty("blog:rate", 0); // If the blog entry has an image if (image.getSize() > 0) { if (image.getContentType().startsWith("image")) { Node imageNode = blogEntryNode.addNode("image", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", image.getInputStream()); contentNode.setProperty("jcr:mimeType", image.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported image format"); request.setAttribute("msgBody", "The image you attached in not supported"); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // If the blog entry has a video if (video.getSize() > 0) { if (video.getName().endsWith(".flv") || video.getName().endsWith(".FLV")) { Node imageNode = blogEntryNode.addNode("video", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", video.getInputStream()); contentNode.setProperty("jcr:mimeType", video.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported video format"); request.setAttribute("msgBody", "Only Flash videos (.flv) are allowed as video attachement. click <a href=\"www.google.com\">here</a> to covert the videos online."); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // persist the changes done session.save(); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Blog entry added succesfully"); request.setAttribute("msgBody", "Blog entry titled \"" + title + "\" was successfully added to your blog space"); request.setAttribute("urlText", "go back to my blog page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/view"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); } catch (RepositoryException e) { throw new ServletException("Repository error occured", e); } finally { if (session != null) { session.logout(); } } }
From source file:org.jxstar.control.action.ActionHelper.java
/** * ?/*from w ww .j a va 2 s.c o m*/ * @param request * @return */ private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException { //? DefaultFileItemFactory factory = new DefaultFileItemFactory(); //? DiskFileUpload upload = new DiskFileUpload(factory); //???? upload.setHeaderEncoding("utf-8"); //?10M String maxSize = SystemVar.getValue("upload.file.maxsize", "10"); upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize)); //? List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { _log.showError(e); throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize); } _log.showDebug("request item size=" + items.size()); // Map<String, Object> requestMap = FactoryUtil.newMap(); // ? Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String key = item.getFieldName(); //????? String value = ""; try { value = item.getString("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (key == null || key.length() == 0) continue; requestMap.put(key, value); } else { String key = item.getFieldName(); requestMap.put(key, item); //?? String fileName = item.getName(); String contentType = item.getContentType(); long fileSize = item.getSize(); _log.showDebug( "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType); } } return requestMap; }
From source file:org.oscarehr.olis.OLISUploadSimulationDataAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*from w w w.jav a 2 s . com*/ Logger logger = MiscUtils.getLogger(); String simulationData = null; boolean simulationError = false; try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); if (name.equals("simulateError")) { simulationError = true; } } else { if (item.getFieldName().equals("simulateFile")) { InputStream is = item.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); simulationData = writer.toString(); } } } if (simulationData != null && simulationData.length() > 0) { if (simulationError) { Driver.readResponseFromXML(request, simulationData); simulationData = (String) request.getAttribute("olisResponseContent"); request.getSession().setAttribute("errors", request.getAttribute("errors")); } request.getSession().setAttribute("olisResponseContent", simulationData); request.setAttribute("result", "File successfully uploaded"); } } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } return mapping.findForward("success"); }