List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.krawler.esp.handlers.fileUploader.java
public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam, ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException { DiskFileUpload fu = new DiskFileUpload(); FileItem fi1 = null; List fileItems = null;//ww w .jav a2 s .co m try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("Admin.createUser", e); } for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); if (fi1.isFormField()) { arrParam.put(fi1.getFieldName(), fi1.getString()); } else { try { String fileName = new String(fi1.getName().getBytes(), "UTF8"); if (fi1.getSize() != 0) { fi.add(fi1); fileUpload = true; } } catch (UnsupportedEncodingException ex) { } } } }
From source file:edu.umd.cs.submitServer.MultipartRequest.java
public static MultipartRequest parseRequest(HttpServletRequest request, int maxSize, Logger logger, boolean strictChecking, ServletContext servletContext) throws IOException, ServletException { DiskFileItemFactory factory = getFactory(servletContext); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxSize);// ww w.ja va 2 s . c o m MultipartRequest multipartRequest = new MultipartRequest(logger, strictChecking); try { // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { multipartRequest.setParameter(item.getFieldName(), item.getString()); } else { multipartRequest.addFileItem(item); } } return multipartRequest; } catch (FileUploadBase.SizeLimitExceededException e) { Debug.error("File upload is too big " + e.getActualSize() + " > " + e.getPermittedSize()); Debug.error("upload info: " + multipartRequest); throw new ServletException(e); } catch (FileUploadException e) { Debug.error("FileUploadException: " + e); throw new ServletException(e); } }
From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java
/** * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, * parses the request, processes the uploaded items and then returns the first file as an * <code>UploadedFile</code> object. * @param portletRequest The input portlet request * @return The first uploaded file object. *//*ww w .jav a 2 s . c om*/ public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) { UploadedFile uploadedFile = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest); // Process the uploaded items Iterator iter = items.iterator(); boolean endLoop = false; while (iter.hasNext() && !endLoop) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //serviceRequest.setAttribute(item.getFieldName(), item.getString()); } else { uploadedFile = new UploadedFile(); uploadedFile.setFileContent(item.get()); uploadedFile.setFieldNameInForm(item.getFieldName()); uploadedFile.setSizeInBytes(item.getSize()); uploadedFile.setFileName(item.getName()); endLoop = true; } } } catch (Exception e) { logger.error("Cannot parse multipart request", e); } return uploadedFile; }
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 {/*w w w. ja v a2 s. c om*/ 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:com.krawler.esp.handlers.fileUploader.java
public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam, ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException { DiskFileUpload fu = new DiskFileUpload(); FileItem fi1 = null; List fileItems = null;/*from w ww.ja v a2s . c o m*/ int i = 0; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("Admin.createUser", e); } for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); try { if (fi1.isFormField()) { arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8")); } else { String fileName = new String(fi1.getName().getBytes(), "UTF8"); if (fi1.getSize() != 0) { fi.add(fi1); filemap.put(i, fi1.getFieldName()); i++; fileUpload = true; } } } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } } }
From source file:dk.clarin.tools.userhandle.java
public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items, String parm) {/*w ww.j av a2 s.c o m*/ logger.debug("parm:[" + parm + "]"); String userHandle = ""; boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request); if (is_multipart_formData) { try { /* logger.debug("In try"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory (); / * *Set the size threshold, above which content will be stored on disk. * / fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB / * * Set the temporary directory to store the uploaded files of size above threshold. * / logger.debug("making tmpDir in " + ToolsProperties.tempdir); File tmpDir = new File(ToolsProperties.tempdir); if(!tmpDir.isDirectory()) { logger.debug("!tmpDir.isDirectory()"); throw new ServletException("Trying to set \"" + ToolsProperties.tempdir + "\" as temporary directory, but this is not a valid directory."); } fileItemFactory.setRepository(tmpDir); * / ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); logger.debug("Now uploadHandler.parseRequest"); List items<FileItem> = uploadHandler.parseRequest(request); */ logger.debug("items:" + items); Iterator<FileItem> itr = items.iterator(); logger.debug("itr:" + itr); while (itr.hasNext()) { logger.debug("in loop"); FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString()); if (item.getFieldName().equals(parm)) { userHandle = item.getString(); logger.debug("Found " + parm + " = " + userHandle); /* if(userId == null && userHandle != null) userId = userhandle.getUserId(request,userHandle); if(userEmail == null && userId != null) userEmail = userhandle.getEmailAddress(request,userHandle,userId); */ break; // currently not interested in other fields than parm } } else if (item.getName() != "") { /* * Write file to the ultimate location. */ logger.debug("File = " + item.getName()); /* We don't handle file upload here data = item.getName(); File file = new File(destinationDir,item.getName()); item.write(file); */ logger.debug("FieldName = " + item.getFieldName()); logger.debug("Name = " + item.getName()); logger.debug("ContentType = " + item.getContentType()); logger.debug("Size = " + item.getSize()); logger.debug("DestinationDir = " + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/); } } } catch (Exception ex) { logger.error("uploadHandler.parseRequest Exception"); } } else { @SuppressWarnings("unchecked") Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames(); for (Enumeration<String> e = parmNames; e.hasMoreElements();) { // Well, you don't get here AT ALL if enctype='multipart/form-data' String parmName = e.nextElement(); logger.debug("parmName:" + parmName); String vals[] = request.getParameterValues(parmName); for (int j = 0; j < vals.length; ++j) { logger.debug("val:" + vals[j]); } } } logger.debug("value[" + parm + "]=" + userHandle); return userHandle; }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */// ww w . j ava2 s.c o m @SuppressWarnings("unchecked") public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string // part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.easyjf.web.core.FrameworkEngine.java
/** * ?requestform/* w w w .j ava 2 s . c om*/ * * @param request * @param formName * @return ??Form */ public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) { Map textElement = new HashMap(); Map fileElement = new HashMap(); String contentType = request.getContentType(); String reMethod = request.getMethod(); if ((contentType != null) && (contentType.startsWith("multipart/form-data")) && (reMethod.equalsIgnoreCase("post"))) { // multipart/form-data File file = new File(request.getSession().getServletContext().getRealPath("/temp")); if (!file.exists()) { file.getParentFile().mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(webConfig.getUploadSizeThreshold()); factory.setRepository(file); ServletFileUpload sf = new ServletFileUpload(factory); sf.setSizeMax(webConfig.getMaxUploadFileSize()); sf.setHeaderEncoding(request.getCharacterEncoding()); List reqPars = null; try { reqPars = sf.parseRequest(request); for (int i = 0; i < reqPars.size(); i++) { FileItem it = (FileItem) reqPars.get(i); if (it.isFormField()) { textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ?? } else { fileElement.put(it.getFieldName(), it);// ??? } } } catch (Exception e) { logger.error(e); } } else if ((contentType != null) && contentType.equals("text/xml")) { StringBuffer buffer = new StringBuffer(); try { String s = request.getReader().readLine(); while (s != null) { buffer.append(s + "\n"); s = request.getReader().readLine(); } } catch (Exception e) { logger.error(e); } textElement.put("xml", buffer.toString()); } else { textElement = request2map(request); } // logger.debug("????"); WebForm wf = findForm(formName); wf.setValidate(module.isValidate());// ?validate?Form if (wf != null) { wf.setFileElement(fileElement); wf.setTextElement(textElement); } return wf; }
From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java
public static Map<String, Object> parsePostedData(String uploadDirPath, HttpServletRequest httpRequest, PrintWriter responseStream) throws Exception { File uploadDir = new File(uploadDirPath); if (!uploadDir.exists()) uploadDir.mkdirs();/*from w w w .j a v a 2 s . c o m*/ Map<String, Object> params = new HashMap<String, Object>(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(httpRequest); Iterator<FileItem> fileItemIterator = items.iterator(); int fileCount = 0; while (fileItemIterator.hasNext()) { FileItem fileItem = fileItemIterator.next(); if (fileItem.isFormField()) { if (params.get(fileItem.getFieldName()) == null) params.put(fileItem.getFieldName(), fileItem.getString()); List values = (List) params.get(fileItem.getFieldName() + "_List"); if (values == null) { values = new ArrayList(); params.put(fileItem.getFieldName() + "_List", values); } values.add(fileItem.getString()); } else { fileCount++; String fieldName = fileItem.getFieldName(); if (fieldName.trim().length() == 0) fieldName = "File" + fileCount; String fileName = fileItem.getName(); log.debug("Uploading file number " + fileCount); log.debug("FieldName: " + fieldName); log.debug("File Name: " + fileName); log.debug("ContentType: " + fileItem.getContentType()); log.debug("Size (Bytes): " + fileItem.getSize()); if (fileItem.getSize() != 0) { try { String tempFileName = "temp" + System.currentTimeMillis() + "-" + fileName; File file = new File(uploadDirPath + "/" + tempFileName); log.debug("FileName: " + file.getAbsolutePath()); // write the file fileItem.write(file); if (params.get(fileItem.getFieldName()) == null) params.put(fileItem.getFieldName(), file); else params.put(fileItem.getFieldName() + fileCount, file); List values = (List) params.get(fileItem.getFieldName() + "_List"); if (values == null) { values = new ArrayList(); params.put(fileItem.getFieldName() + "_List", values); } values.add(file); } catch (Exception e) { e.printStackTrace(); log.warning("Error receiving file:" + e); responseStream.print("error reading (" + fileCount + "): " + fileItem.getName()); continue; } } } } return params; }
From source file:com.krawler.esp.servlets.SuperAdminServlet.java
public static String editCompany(Connection conn, HttpServletRequest request, HttpServletResponse response) throws ServiceException { String status = ""; DiskFileUpload fu = new DiskFileUpload(); JSONObject j = new JSONObject(); JSONObject j1 = new JSONObject(); List fileItems = null;/*from ww w .j av a2 s . c o m*/ FileItem fi1 = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e); } HashMap arrParam = new HashMap(); for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); arrParam.put(fi1.getFieldName(), fi1.getString()); } try { DbUtil.executeUpdate(conn, "update company set companyname=?, address=?, city=?, state=?, country=?, phone=?, fax=?, " + "zip=?, timezone=?, website=? where companyid=?;", new Object[] { arrParam.get("companyname"), arrParam.get("address"), arrParam.get("city"), arrParam.get("state"), arrParam.get("country"), arrParam.get("phone"), arrParam.get("fax"), arrParam.get("zip"), arrParam.get("timezone"), arrParam.get("website"), arrParam.get("companyid") }); j.put("companyname", arrParam.get("companyname")); j.put("address", arrParam.get("address")); j.put("city", arrParam.get("city")); j.put("state", arrParam.get("state")); j.put("country", arrParam.get("country")); j.put("phone", arrParam.get("phone")); j.put("fax", arrParam.get("fax")); j.put("zip", arrParam.get("zip")); j.put("timezone", arrParam.get("timezone")); j.put("website", arrParam.get("website")); j.put("companyid", arrParam.get("companyid")); if (arrParam.get("image").toString().length() != 0) { genericFileUpload uploader = new genericFileUpload(); try { uploader.doPost(fileItems, arrParam.get("companyid").toString(), StorageHandler.GetProfileImgStorePath()); } catch (ConfigurationException e) { throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e); } if (uploader.isUploaded()) { DbUtil.executeUpdate(conn, "update company set image=? where companyid = ?", new Object[] { ProfileImageServlet.ImgBasePath + arrParam.get("companyid").toString() + uploader.getExt(), arrParam.get("companyid") }); j.put("image", arrParam.get("companyid") + uploader.getExt()); } } j1.append("data", j); status = j1.toString(); } catch (JSONException e) { status = "failure"; throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e); } return status; }