List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.zlfun.framework.misc.UploadUtils.java
public static byte[] getFileBytes(HttpServletRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); // ???//from ww w. j a v a2s . 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: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 . j a va 2 s. c o 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.exilant.exility.core.XLSHandler.java
/** * @param req/*from w w w. j a va 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 w w w. j ava2 s . c om * @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:httpUtils.HttpUtils.java
/** * Parse the httpServletRequest for the file item that was received within a * multipart/form-data POST request/* ww w . j av a2s . co m*/ * @param httpServletRequest * @return the file item */ public static DiskFileItem parseRequestForFileItem(HttpServletRequest httpServletRequest) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request for file List<FileItem> items = null; try { items = upload.parseRequest(httpServletRequest); } catch (FileUploadException fue) { log.error("Error reading/parsing file", fue); } if (items.size() != 1) { log.debug("there should only be one file here."); for (FileItem x : items) { log.debug("item: " + x.toString()); } } DiskFileItem dfi = (DiskFileItem) items.get(0); log.debug("parseRequestForFile - store location: `" + dfi.getStoreLocation() + "'"); log.debug("dfi content type: " + dfi.getContentType()); return dfi; }
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} *//*from w w w. ja va 2 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: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();//ww w . j a va2s .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 {//from w ww . j a va2 s .c o 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.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
/** * ???????/*from ww w .j a va2 s . co 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.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 .j a v a 2s. co 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); } }