List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.exilant.exility.core.XLSHandler.java
/** * @param req/* ww w .jav a 2 s . c o m*/ * @param container * @return whether we are able to parse it */ @SuppressWarnings("unchecked") public static boolean parseMultiPartData(HttpServletRequest req, ServiceData container) { /** * I didnt check here for multipart request ?. caller should check. */ 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 = null; try { items = sFileUpload.parseRequest(req); } catch (FileUploadException e) { container.addMessage("fileUploadFailed", e.getMessage()); Spit.out(e); return false; } /* * If user is asked for multiple file upload with filesPathGridName then * create a grid with below columns and send to the client/DC */ String filesPathGridName = req.getHeader("filesPathGridName"); OutputColumn[] columns = { new OutputColumn("fileName", DataValueType.TEXT, "fileName"), new OutputColumn("fileSize", DataValueType.INTEGRAL, "fileSize"), new OutputColumn("filePath", DataValueType.TEXT, "filePath") }; Value[] columnValues = null; FileItem f = null; String allowMultiple = req.getHeader("allowMultiple"); List<Value[]> rows = new ArrayList<Value[]>(); String fileNameWithPath = ""; String rootPath = getResourcePath(); String fileName = null; int fileCount = 0; for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); container.addValue(name, item.getString()); } else { f = item; if (allowMultiple != null) { fileCount++; fileName = item.getName(); fileNameWithPath = rootPath + getUniqueName(fileName); String path = XLSHandler.write(item, fileNameWithPath, container); if (path == null) { return false; } if (filesPathGridName != null && filesPathGridName.length() > 0) { columnValues = new Value[3]; columnValues[0] = Value.newValue(fileName); columnValues[1] = Value.newValue(f.getSize()); columnValues[2] = Value.newValue(fileNameWithPath); rows.add(columnValues); fileNameWithPath = ""; continue; } container.addValue("file" + fileCount + "_ExilityPath", fileNameWithPath); fileNameWithPath = ""; } } } if (f != null && allowMultiple == null) { fileNameWithPath = rootPath + getUniqueName(f.getName()); String path = XLSHandler.write(f, fileNameWithPath, container); if (path == null) { return false; } container.addValue(container.getValue("fileFieldName"), path); return true; } /** * If user asked for multiple file upload and has supplied gridName for * holding the file path then create a grid */ if (rows.size() > 0) { Grid aGrid = new Grid(filesPathGridName); aGrid.setValues(columns, rows, null); container.addGrid(filesPathGridName, aGrid.getRawData()); } return true; }
From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java
/** * ?request?fireDir?request.setAttribute(fieldName, value)? * * @param request /*from www. j a v a 2s. c o m*/ * @param fileDir * @param maxSize ? * @param isFileNameBaseTime ???? * @param encoding */ public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize, boolean isFileNameBaseTime, String encoding) { // ? if (!isFileUploadRequest(request)) return null; DiskFileItemFactory factory = new DiskFileItemFactory(); // dir?? File dir = new File(fileDir); if (!dir.exists()) { if (dir.mkdirs()) { throw new FileDirFaultException(dir); } ; } if (maxSize > 0) { factory.setSizeThreshold(maxSize); } factory.setRepository(dir); // ? ServletFileUpload fileUploader = new ServletFileUpload(factory); fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding); String realEncoding = fileUploader.getHeaderEncoding(); List<FileItem> items = null; try { items = fileUploader.parseRequest(request); } catch (FileUploadException e1) { e1.printStackTrace(); } if (items == null) return null; FileUploadRequestParamterContext context = new FileUploadRequestParamterContext(); Map<String, List<File>> fileMap = context.getFileMap(); Map<String, List<String>> fieldMap = context.getFormFieldMap(); FileItem fileItem = null; Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { fileItem = iter.next(); String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { List<String> values = fieldMap.get(fieldName); if (values == null) { values = new ArrayList<String>(); fieldMap.put(fieldName, values); } String value = null; try { value = fileItem.getString(realEncoding); } catch (UnsupportedEncodingException e) { value = ""; e.printStackTrace(); } values.add(value); log.info("param:\t" + fieldName + "=" + value); } else { List<File> files = fileMap.get(fieldName); if (files == null) { files = new ArrayList<File>(); fileMap.put(fieldName, files); } String clientFileName = fileItem.getName();// ??? if (StringUtil.isNull(clientFileName)) { // continue; } String realFileName = FileUtil.getRealFileName(clientFileName); String newFileName = null; if (isFileNameBaseTime) { newFileName = new FileNameBuilder().build(realFileName); } else { newFileName = realFileName; } File tempfile = new File(dir, newFileName); try { fileItem.write(tempfile); log.info("???\t" + newFileName); files.add(tempfile); } catch (Exception e) { continue; } } } return null; }
From source file:jeeves.server.sources.ServiceRequestFactory.java
private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize) throws Exception { Element params = new Element("params"); DiskFileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(fif); sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L); try {//from w w w . ja v a2 s. c om for (Object i : sfu.parseRequest(req)) { FileItem item = (FileItem) i; String name = item.getFieldName(); if (item.isFormField()) { String encoding = req.getCharacterEncoding(); params.addContent(new Element(name).setText(item.getString(encoding))); } else { String file = item.getName(); String type = item.getContentType(); long size = item.getSize(); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size); //--- remove path information from file (some browsers put it, like IE) file = simplifyName(file); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "File is called " + file + " after simplification"); //--- we could get troubles if 2 users upload files with the same name item.write(new File(uploadDir, file)); Element elem = new Element(name).setAttribute("type", "file") .setAttribute("size", Long.toString(size)).setText(file); if (type != null) elem.setAttribute("content-type", type); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem)); params.addContent(elem); } } } catch (FileUploadBase.SizeLimitExceededException e) { throw new FileUploadTooBigEx(); } return params; }
From source file:com.zimbra.cs.servlet.util.CsrfUtil.java
public static boolean checkCsrfInMultipartFileUpload(List<FileItem> items, AuthToken at) { for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals(PARAM_CSRF_TOKEN)) { if (item.getSize() < 128) { // if the value is larger, it is not a CSRF token String csrfToken = item.getString(); if (CsrfUtil.isValidCsrfToken(csrfToken, at)) { return true; } else { ZimbraLog.misc.debug("Csrf token : %s recd in file upload is invalid.", csrfToken); }//w w w .j a v a 2s . com } break; } } } return false; }
From source file:com.zlfun.framework.misc.UploadUtils.java
public static byte[] getFileBytes(HttpServletRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); // ???// w w w . j a va 2s . co m // ?? DiskFileItemFactory factory = new DiskFileItemFactory(); // ?? // ?? factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { // ? List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // ???? String name = item.getFieldName(); // ? ?? ? if (item.isFormField()) { // ? ?????? String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8"); request.setAttribute(name, value); } // ? ?? else { /** * ?? ?? */ // ??? String value = item.getName(); // ? // ???? value = java.net.URLDecoder.decode(value, "UTF-8"); int start = value.lastIndexOf("\\"); // ? ??1 ??? String filename = value.substring(start + 1); InputStream in = item.getInputStream(); int length = 0; byte[] buf = new byte[1024]; System.out.println("??" + item.getSize()); // in.read(buf) ?? buf while ((length = in.read(buf)) != -1) { // buf ?? ?? out.write(buf, 0, length); } try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); } return out.toByteArray(); } } } catch (Exception e) { e.printStackTrace(); return null; } finally { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e); } } return null; }
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);//from w w w. ja v a2 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: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;/*from 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:jeeves.server.sources.JeevletServiceRequestFactory.java
private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception { Element params = new Element("params"); // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ... // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // The Apache FileUpload project parses HTTP requests which // conform to RFC 1867, "Form-based File Upload in HTML". That // is, if an HTTP request is submitted using the POST method, // and with a content type of "multipart/form-data", then // FileUpload can parse that request, and get all uploaded files // as FileItem. // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // en mmoire factory.setRepository(new File(uploadDir)); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); upload.setFileSizeMax(maxUploadSize * 1024 * 1024); List<FileItem> items;/*from ww w. ja va 2s . c om*/ try { items = upload.parseRequest(req);// parseRepresentation(req.getEntity()); for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); if (item.isFormField()) params.addContent(new Element(name).setText(item.getString())); else { String file = item.getName(); String type = item.getContentType(); long size = item.getSize(); Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size); //--- remove path information from file (some browsers put it, like IE) file = simplifyName(file); Log.debug(Log.REQUEST, "File is called " + file + " after simplification"); //--- we could get troubles if 2 users upload files with the same name item.write(new File(uploadDir, file)); Element elem = new Element(name).setAttribute("type", "file") .setAttribute("size", Long.toString(size)).setText(file); if (type != null) elem.setAttribute("content-type", type); Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem)); params.addContent(elem); } } } catch (FileUploadBase.FileSizeLimitExceededException e) { // throw jeeves exception --> reached code ? see apache docs - // FileUploadBase throw new FileUploadTooBigEx(); } catch (FileUploadException e) { // Sample Restlet ... " // The message of all thrown exception is sent back to client as simple plain text // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN)); // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); // e.printStackTrace(); // " ... now throw a JeevletException but // FIXME must throw Exception with a correct Status throw new JeevletException(e); } return params; }
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} *///w w w.ja v a 2 s . com @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:dk.clarin.tools.userhandle.java
public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items, String parm) {//from w w w . j av a 2s .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; }