List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.zlfun.framework.misc.UploadUtils.java
public static byte[] getFileBytes(HttpServletRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); // ???/*from w w w . j av a 2 s . c om*/ // ?? 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:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object./* w ww. j a v a 2 s. c om*/ * @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.aaasec.sigserv.csspserver.utility.SpServerLogic.java
public static String processFileUpload(HttpServletRequest request, HttpServletResponse response, RequestModel req) {/*from w w w . j a v a2 s. c o 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: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 ww . j a va 2s .co m*/ 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.fjn.helper.common.io.file.upload.FileUploadHelper.java
/** * ?request?fireDir?request.setAttribute(fieldName, value)? * * @param request // w w w .j av a 2 s . com * @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:com.krawler.esp.servlets.SuperAdminServlet.java
public static String createCompany(Connection conn, HttpServletRequest request, HttpServletResponse response) throws ServiceException { String status = ""; DiskFileUpload fu = new DiskFileUpload(); ResultSet frs = null, ars = null; PreparedStatement pstmt = null, fpstmt = null, apstmt = null; double val = 0.0; List fileItems = null;/*from w w w . j a v a 2 s.co m*/ try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e); } HashMap arrParam = new HashMap(); for (Iterator k = fileItems.iterator(); k.hasNext();) { FileItem fi1 = (FileItem) k.next(); arrParam.put(fi1.getFieldName(), fi1.getString()); } String companyid = UUID.randomUUID().toString(); /*DbUtil .executeUpdate( conn, "insert into company(companyid, companyname, createdon, address, city, state, country, phone, fax, zip, " + "timezone, website) values (?, ?, now(), ?, ?, ?, ?, ?, ?, ?, ?, ?);", new Object[] { companyid, 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") });*/ java.util.Date d = new java.util.Date(); java.sql.Timestamp today = new Timestamp(d.getTime()); DbUtil.executeUpdate(conn, "INSERT INTO company(companyid, companyname, address, createdon, website) values (?,?,?,?,?);", new Object[] { companyid, arrParam.get("companyname"), arrParam.get("address"), today, arrParam.get("website") }); String userid = UUID.randomUUID().toString(); String newPass = AuthHandler.generateNewPassword(); String newPassSHA1 = AuthHandler.getSHA1(newPass); DbUtil.executeUpdate(conn, "insert into userlogin(userid, username, password, authkey) values (?,?,?,?);", new Object[] { userid, arrParam.get("username"), newPassSHA1, newPass }); DbUtil.executeUpdate(conn, "insert into users(userid, companyid, image) values (?,?,?);", new Object[] { userid, companyid, "" }); try { fpstmt = conn.prepareStatement("SELECT featureid FROM featurelist"); frs = fpstmt.executeQuery(); while (frs.next()) { apstmt = conn.prepareStatement("SELECT activityid FROM activitieslist WHERE featureid=?"); apstmt.setInt(1, frs.getInt("featureid")); ars = apstmt.executeQuery(); while (ars.next()) { val += Math.pow(2, Double.parseDouble(ars.getString("activityid"))); } pstmt = conn.prepareStatement( "INSERT INTO userpermissions (userid, featureid, permissions) VALUES (?,?,?)"); pstmt.setString(1, userid); pstmt.setInt(2, frs.getInt("featureid")); pstmt.setInt(3, (int) val); pstmt.executeUpdate(); val = 0.0; } } catch (SQLException e) { throw ServiceException.FAILURE("signup.confirmSignup", e); } finally { DbPool.closeStatement(pstmt); } if (arrParam.get("image").toString().length() != 0) { genericFileUpload uploader = new genericFileUpload(); try { uploader.doPost(fileItems, companyid, 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 + companyid + uploader.getExt(), companyid, companyid }); } } status = "success"; return status; }
From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
/** * ???????//from w w w . ja v 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:com.exilant.exility.core.XLSHandler.java
/** * @param req//from w w w .j a v a 2 s .c om * @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: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 w ww . jav a 2 s .c o m 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.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); }/*from w ww. ja v a2 s .c o m*/ } break; } } } return false; }