List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object.// w ww . j a va 2 s . 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: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. *//* w ww . j a v a 2 s.co m*/ 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:com.exilant.exility.core.XLSHandler.java
/** * This method returns FileItem handler out of file field in HTTP request * //from ww w . ja v a 2 s.c om * @param req * @return FileItem * @throws IOException * @throws FileUploadException */ @SuppressWarnings("unchecked") public static FileItem getFileItem(HttpServletRequest req) throws IOException, FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); /* * we can increase the in memory size to hold the file data but its * inefficient so ignoring to factory.setSizeThreshold(20*1024); */ ServletFileUpload sFileUpload = new ServletFileUpload(factory); List<FileItem> items = sFileUpload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { return item; } } throw new FileUploadException("File field not found"); }
From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java
public static String processFileUpload(HttpServletRequest request, HttpServletResponse response, RequestModel req) {//from ww w .j a va2 s .co m // Create a factory for disk-based file items Map<String, String> paraMap = new HashMap<String, String>(); File uploadedFile = null; boolean uploaded = false; DiskFileItemFactory factory = new DiskFileItemFactory(); String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads"); FileOps.createDir(uploadDirName); File storageDir = new File(uploadDirName); factory.setRepository(storageDir); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); paraMap.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName.length() > 0) { String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); uploadedFile = new File(storageDir, fileName); try { item.write(uploadedFile); uploaded = true; } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } } } if (uploaded) { return SpServerLogic.getDocUploadResponse(req, uploadedFile); } else { if (paraMap.containsKey("xmlName")) { return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName")); } } } catch (FileUploadException ex) { LOG.log(Level.SEVERE, null, ex); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); return ""; }
From source file:com.silverpeas.util.i18n.I18NHelper.java
static private String getParameterValue(List<FileItem> items, String parameterName) { for (FileItem item : items) { if (item.isFormField() && parameterName.equals(item.getFieldName())) { return item.getString(); }//from ww w .j a va2 s. c o m } return null; }
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Replacement for and wrapper around/*from w ww. j a va2 s . c o m*/ * HttpServletRequest.getParameter(String) which works for multi-part form * data as well as normal requests */ public static String getParameter(HttpServletRequest request, String parameterName, List<FileItem> multipartItems) { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { for (FileItem item : multipartItems) { if (item.getFieldName().equals(parameterName)) { if (item.isFormField()) { return item.getString(); } else { return item.getName(); } } } return null; } else { return request.getParameter(parameterName); } }
From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
/** * ???????//from w ww . j av a2s . c o m * @param klass ???klass?Class * @param filepath ? * @param sizeThreshold ?? * @param isFileNameBaseTime ???? * @return bean */ public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold, boolean isFileNameBaseTime) throws Exception { FileItemFactory fileItemFactory = null; if (sizeThreshold > 0) { File repository = new File(filepath); fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository); } else { fileItemFactory = new DiskFileItemFactory(); } ServletFileUpload upload = new ServletFileUpload(fileItemFactory); ServletRequestContext requestContext = new ServletRequestContext(request); T bean = null; if (klass != null) { bean = klass.newInstance(); } // if (ServletFileUpload.isMultipartContent(requestContext)) { File parentDir = new File(filepath); List<FileItem> fileItemList = upload.parseRequest(requestContext); for (int i = 0; i < fileItemList.size(); i++) { FileItem item = fileItemList.get(i); // ?? if (item.isFormField()) { String paramName = item.getFieldName(); String paramValue = item.getString("UTF-8"); log.info("?" + paramName + "=" + paramValue); request.setAttribute(paramName, paramValue); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); Class type = field.getType(); if (type == Integer.TYPE) { field.setInt(bean, Integer.valueOf(paramValue)); } else if (type == Double.TYPE) { field.setDouble(bean, Double.valueOf(paramValue)); } else if (type == Float.TYPE) { field.setFloat(bean, Float.valueOf(paramValue)); } else if (type == Boolean.TYPE) { field.setBoolean(bean, Boolean.valueOf(paramValue)); } else if (type == Character.TYPE) { field.setChar(bean, paramValue.charAt(0)); } else if (type == Long.TYPE) { field.setLong(bean, Long.valueOf(paramValue)); } else if (type == Short.TYPE) { field.setShort(bean, Short.valueOf(paramValue)); } else { field.set(bean, paramValue); } } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "?" + paramName); } } } // else { // <input type='file' name='xxx'> xxx String paramName = item.getFieldName(); log.info("?" + item.getSize()); if (sizeThreshold > 0) { if (item.getSize() > sizeThreshold) continue; } String clientFileName = item.getName(); int index = -1; // ?IE? if ((index = clientFileName.lastIndexOf("\\")) != -1) { clientFileName = clientFileName.substring(index + 1); } if (clientFileName == null || "".equals(clientFileName)) continue; String filename = null; log.info("" + paramName + "\t??" + clientFileName); if (isFileNameBaseTime) { filename = buildFileName(clientFileName); } else filename = clientFileName; request.setAttribute(paramName, filename); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); field.set(bean, filename); } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "? " + paramName); continue; } } if (!parentDir.exists()) { parentDir.mkdirs(); } File newfile = new File(parentDir, filename); item.write(newfile); String serverPath = newfile.getPath(); log.info("?" + serverPath); } } } return bean; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java
private static void parseFileParts(HttpServletRequest req, ListsMap<String> parameters, ListsMap<FileItem> files, ParsingStrategy strategy) throws IOException { ServletFileUpload upload = createUploadHandler(req, strategy.maximumMultipartFileSize()); List<FileItem> items = parseRequestIntoFileItems(req, upload, strategy); for (FileItem item : items) { // Process a regular form field String name = item.getFieldName(); if (item.isFormField()) { String value;//w w w . jav a 2s .c o m try { value = item.getString("UTF-8"); } catch (UnsupportedEncodingException e) { value = item.getString(); } parameters.add(name, value); log.debug("Form field (parameter) " + name + "=" + value); } else { files.add(name, item); log.debug("File " + name + ": " + item.getSize() + " bytes."); } } }
From source file:com.openmeap.util.ServletUtils.java
/** * @param modelManager//from ww w . j av a2s. c o m * @param request * @param map * @return * @throws FileUploadException */ static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix, HttpServletRequest request, Map<Object, Object> map) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(fileStoragePrefix)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileUploadSize); List fileItems = upload.parseRequest(request); for (FileItem item : (List<FileItem>) fileItems) { // we'll put this in the parameter map, // assuming the backing that is looking for it // knows what to expect String fieldName = item.getFieldName(); Boolean isFormField = item.isFormField(); Long size = item.getSize(); if (isFormField) { if (size > 0) { map.put(fieldName, new String[] { item.getString() }); } } else if (!isFormField) { map.put(fieldName, item); } } return true; }
From source file:com.krawler.esp.portalmsg.forummsgcomm.java
public static void doPost(Connection conn, java.util.List fileItems, String postid, java.sql.Timestamp docdatemod, String userid, String sendefolderpostid) throws ServiceException { try {//from w w w.j av a 2s .c om String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "attachment"; java.io.File destDir = new java.io.File(destinationDirectory); String Ext = ""; if (!destDir.exists()) { destDir.mkdirs(); } String fileid; long size; org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload(); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); for (java.util.Iterator i = fileItems.iterator(); i.hasNext();) { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; fileid = UUID.randomUUID().toString(); try { fileName = getFileName(fi); // fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } size = fi.getSize(); if (size != 0) { File uploadFile = new File(destinationDirectory + "/" + fileid + Ext); fi.write(uploadFile); fildoc(conn, fileid, fileName, docdatemod, postid, fileid + Ext, userid, size, sendefolderpostid); } } catch (Exception e) { throw ServiceException.FAILURE("ProfileHandler.updateProfile", e); } } } } catch (ConfigurationException ex) { Logger.getLogger(forummsgcomm.class.getName()).log(Level.SEVERE, null, ex); } }