List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. 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 . j ava 2s. co 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:com.easyjf.web.core.FrameworkEngine.java
/** * ?requestform/*w ww . ja v a 2 s . com*/ * * @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 www.j a v a 2s . 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.zving.cms.site.Site.java
public static void uploadSite(HttpServletRequest request, HttpServletResponse response) { try {//www . ja v a 2s . co m DiskFileItemFactory fileFactory = new DiskFileItemFactory(); ServletFileUpload fu = new ServletFileUpload(fileFactory); List fileItems = fu.parseRequest(request); fu.setHeaderEncoding("UTF-8"); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!(item.isFormField())) { String OldFileName = item.getName(); LogUtil.info("Upload Site FileName:" + OldFileName); long size = item.getSize(); if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) { continue; } OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1); String ext = OldFileName.substring(OldFileName.lastIndexOf(".")); if (!(ext.toLowerCase().equals(".dat"))) { response.sendRedirect("SiteImportStep1.jsp?Error=1"); return; } String FileName = "SiteUpload_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat"; String Path = Config.getContextRealPath() + "WEB-INF/data/backup/"; item.write(new File(Path + FileName)); response.sendRedirect("SiteImportStep2.jsp?FileName=" + FileName); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.xpn.xwiki.web.Utils.java
/** * Process a multi-part request, extracting all the uploaded files. * /*from w w w . jav a 2 s .c om*/ * @param request the current request to process * @param context the current context * @return the instance of the {@link FileUploadPlugin} used to parse the uploaded files */ public static FileUploadPlugin handleMultipart(HttpServletRequest request, XWikiContext context) { FileUploadPlugin fileupload = null; try { if (request instanceof MultipartRequestWrapper) { fileupload = new FileUploadPlugin("fileupload", "fileupload", context); fileupload.loadFileList(context); context.put("fileuploadplugin", fileupload); MultipartRequestWrapper mpreq = (MultipartRequestWrapper) request; List<FileItem> fileItems = fileupload.getFileItems(context); for (FileItem item : fileItems) { if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(context.getWiki().getEncoding()); mpreq.setParameter(sName, sValue); } } } } catch (Exception e) { if ((e instanceof XWikiException) && (((XWikiException) e).getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE)) { context.put("exception", e); } else { e.printStackTrace(); } } return fileupload; }
From source file:com.krawler.esp.handlers.basecampHandler.java
public static File getfile(HttpServletRequest request, String docid) throws ConfigurationException { String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "baseCamxml"; java.io.File destDir = new java.io.File(destinationDirectory); if (!destDir.exists()) { destDir.mkdirs();/* ww w . j a v a2 s . com*/ } DiskFileUpload fu = new DiskFileUpload(); String Ext = null; File uploadFile = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (fi.getSize() != 0) { uploadFile = new File( destinationDirectory + StorageHandler.GetFileSeparator() + docid + ".xml"); fi.write(uploadFile); } } catch (Exception e) { KrawlerLog.op.warn("Problem While Reading file :" + e.toString()); } } } return uploadFile; }
From source file:com.dien.upload.server.UploadServlet.java
/** * Utility method to get a fileItem from a vector using the file name It * only returns items of type file./* w ww. ja va 2 s . c o m*/ * * @param sessionFiles * @param fileName * @return fileItem of the file found or null */ public static FileItem findItemByFileName(List<FileItem> sessionFiles, String fileName) { if (sessionFiles != null) { for (FileItem fileItem : sessionFiles) { if (fileItem.isFormField() == false && fileItem.getName().equalsIgnoreCase(fileName)) { return fileItem; } } } return null; }
From source file:com.dien.upload.server.UploadServlet.java
/** * Removes all FileItems stored in session, but in this case * the user can specify whether the temporary data is removed from disk. * /*from w w w . ja va2 s . co m*/ * @param request * @param removeData * true: the file data is deleted. * false: use it when you are referencing file items * instead of copying them. */ public static void removeSessionFileItems(HttpServletRequest request, boolean removeData) { logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeSessionFileItems: removeData=" + removeData); @SuppressWarnings("unchecked") Vector<FileItem> sessionFiles = (Vector<FileItem>) request.getSession().getAttribute(SESSION_FILES); if (removeData && sessionFiles != null) { for (FileItem fileItem : sessionFiles) { if (fileItem != null && !fileItem.isFormField()) { fileItem.delete(); } } } request.getSession().removeAttribute(SESSION_FILES); }
From source file:com.zlfun.framework.excel.ExcelUtils.java
public static <T> List<T> httpInput(HttpServletRequest request, Class<T> clazz) { List<T> result = new ArrayList<T>(); //?? //from w ww. java 2s. c om DiskFileItemFactory factory = new DiskFileItemFactory(); //?? String path = request.getSession().getServletContext().getRealPath("/"); factory.setRepository(new File(path)); // ?? factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); try { //? List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { //???? String name = item.getFieldName(); //? ?? ? if (item.isFormField()) { //? ?????? String value = item.getString(); request.setAttribute(name, value); } //? ?? else { /** * ?? ?? */ //??? String value = item.getName(); //???? fill(clazz, result, value, item.getInputStream()); //?? } } } catch (FileUploadException ex) { // TODO Auto-generated catch block excel=null; Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:com.dien.upload.server.UploadServlet.java
/** * Utility method to get a fileItem of type file from a vector using either * the file name or the attribute name./*www. jav a2 s .c o m*/ * * @param sessionFiles * @param parameter * @return fileItem of the file found or null */ public static FileItem findFileItem(List<FileItem> sessionFiles, String parameter) { if (sessionFiles == null || parameter == null) { return null; } FileItem item = findItemByFieldName(sessionFiles, parameter); if (item == null) { item = findItemByFileName(sessionFiles, parameter); } if (item != null && !item.isFormField()) { return item; } return null; }