List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.intbit.FileUploadUtil.java
public static String uploadFile(String uploadPath, HttpServletRequest request) throws FileUploadException, Exception { logger.info("FileUploadUtil::Entering FileUploadUtil#uploadFile"); String fileName = null;/*from w w w . j a v a 2 s .c o m*/ logger.info("FileUploadUtil::Upload path without filename: " + uploadPath); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!(fi.isFormField())) { // Get the uploaded file parameters fileName = fi.getName(); if (!"".equals(fileName)) { File uploadDir = new File(uploadPath); boolean result = false; if (!uploadDir.exists()) { result = uploadDir.mkdirs(); } // Write the file String filePath = uploadPath + File.separator + fileName; logger.info("FileUploadUtil::Upload path with filename" + filePath); File storeFile = new File(filePath); fi.write(storeFile); logger.info("FileUploadUtil::File Uploaded successfully"); } else { throw new IllegalArgumentException("Filename of uploded file cannot be empty"); } } } return fileName; }
From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
/** * Reads a {@code "multipart/form"} HTTP request body into a {@link Body} * instance or fails with a {@link BadRequestException} if the input is not * a valid multipart form./*from www.j a v a2 s . c o m*/ * * @review */ public static Body multipartToBody(HttpServletRequest request) { if (!isMultipartContent(request)) { throw new BadRequestException("Request body is not a valid multipart form"); } FileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); try { List<FileItem> fileItems = servletFileUpload.parseRequest(request); Iterator<FileItem> iterator = fileItems.iterator(); Map<String, String> values = new HashMap<>(); Map<String, BinaryFile> binaryFiles = new HashMap<>(); Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>(); Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); String name = fileItem.getFieldName(); Matcher matcher = _arrayPattern.matcher(name); if (matcher.matches()) { int index = Integer.parseInt(matcher.group(2)); String actualName = matcher.group(1); _storeFileItem(fileItem, value -> { Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName, __ -> new HashMap<>()); indexedMap.put(index, value); }, binaryFile -> { Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName, __ -> new HashMap<>()); indexedMap.put(index, binaryFile); }); } else { _storeFileItem(fileItem, value -> values.put(name, value), binaryFile -> binaryFiles.put(name, binaryFile)); } } Map<String, List<String>> valueLists = _flattenMap(indexedValueLists); Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists); return Body.create(key -> Optional.ofNullable(values.get(key)), key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)), key -> Optional.ofNullable(binaryFiles.get(key))); } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) { throw new BadRequestException("Request body is not a valid multipart form", e); } }
From source file:com.zving.platform.SysInfo.java
public static void uploadDB(HttpServletRequest request, HttpServletResponse response) { try {/*from www .java 2s.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(); System.out.println("Upload DB 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("DBUpload.jsp?Error=?dat?"); return; } final String FileName = Config.getContextRealPath() + "WEB-INF/data/backup/DBUpload_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat"; item.write(new File(FileName)); LongTimeTask ltt = LongTimeTask.getInstanceByType("Install"); if (ltt != null) { response.sendRedirect("DBUpload.jsp?Error=??"); return; } SessionListener.forceExit(); Config.isAllowLogin = false; ltt = new LongTimeTask() { public void execute() { DBImport di = new DBImport(); di.setTask(this); di.importDB(FileName, "Default"); setPercent(100); Config.loadConfig(); CronManager.getInstance().init(); } }; ltt.setType("Install"); ltt.setUser(User.getCurrent()); ltt.start(); response.sendRedirect("DBUpload.jsp?TaskID=" + ltt.getTaskID()); } } } catch (Exception e) { e.printStackTrace(); } finally { Config.isAllowLogin = true; } }
From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java
public static Iterator<FileItem> createFactory(HttpServletRequest request, HttpServletResponse response) throws Exception { try {// w w w . j av a 2s . com // ?? servletFileUplaod DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // ?request??inputFileInput List<FileItem> fileItemList = servletFileUpload.parseRequest(request); return fileItemList.iterator(); } catch (Exception e) { e.printStackTrace(); throw new Exception("?!"); } }
From source file:in.xebia.poc.FileUploadUtils.java
public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile, Map<String, String> params) throws Exception { log.debug("Request class? " + request.getClass().toString()); log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request)); log.debug("Request method: " + request.getMethod()); log.debug("Request params: "); for (Object key : request.getParameterMap().keySet()) { log.debug((String) key);/* w w w . j a v a 2 s.c om*/ } log.debug("Request attribute names: "); boolean filedataInAttributes = false; Enumeration attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); log.debug(attrName); if ("filedata".equals(attrName)) { filedataInAttributes = true; } } if (filedataInAttributes) { log.debug("Found filedata in request attributes, getting it out..."); log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString()); FileItem item = (FileItem) request.getAttribute("filedata"); item.write(outputFile); for (Object key : request.getParameterMap().keySet()) { params.put((String) key, request.getParameter((String) key)); } return true; } /*ServletFileUpload upload = new ServletFileUpload(); //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE); FileItemIterator iter = upload.getItemIterator(request); while(iter.hasNext()){ FileItemStream item = iter.next(); InputStream stream = item.openStream(); //If this item is a file if(!item.isFormField()){ log.debug("Found non form field in upload request with field name = " + item.getFieldName()); String name = item.getName(); if(name == null){ throw new Exception("File upload did not have filename specified"); } // Some browsers, including IE, return the full path so trim off everything but the file name name = getFileNameFromPath(name); //Enforce required file extension, if present if(!name.toLowerCase().endsWith( ".zip" )){ throw new Exception("File uploaded did not have required extension .zip"); } bufferedCopyStream(stream, new FileOutputStream(outputFile)); } else { params.put(item.getFieldName(), Streams.asString(stream)); } } return true;*/ // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { log.debug("Found non form field in upload request with field name = " + item.getFieldName()); String name = item.getName(); if (name == null) { throw new Exception("File upload did not have filename specified"); } // Some browsers, including IE, return the full path so trim off everything but the file name name = getFileNameFromPath(name); item.write(outputFile); } else { params.put(item.getFieldName(), item.getString()); } } return true; }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);/*from ww w .jav a 2 s. c om*/ // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Provide the ability to cache multi-part items in a variable to save re-parsing *///ww w. j a v a 2s . co m public static List<FileItem> getMultipartItems(HttpServletRequest request) { List<FileItem> multipartItems = new LinkedList<FileItem>(); if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { // See http://jakarta.apache.org/commons/fileupload/using.html FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { multipartItems = upload.parseRequest(request); } catch (FileUploadException fuex) { logException(fuex, request, "Error parsing multi-part form data"); } } return multipartItems; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java
/** * Parse the raw request into a list of parts. * // ww w . j a v a 2 s .co m * If there is a parsing error, let the strategy handle it. If the strategy * throws it back, wrap it in an IOException and throw it on up. */ @SuppressWarnings("unchecked") private static List<FileItem> parseRequestIntoFileItems(HttpServletRequest req, ServletFileUpload upload, ParsingStrategy strategy) throws IOException { try { return upload.parseRequest(req); } catch (FileSizeLimitExceededException | SizeLimitExceededException e) { if (strategy.stashFileSizeException()) { req.setAttribute(ATTRIBUTE_FILE_SIZE_EXCEPTION, e); return Collections.emptyList(); } else { throw new IOException(e); } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:edu.isi.webserver.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request) { // Download the file to the upload file folder File destinationDir = new File(DESTINATION_DIR_PATH); logger.info("File upload destination directory: " + destinationDir.getAbsolutePath()); if (!destinationDir.isDirectory()) { destinationDir.mkdir();// w ww. j a va 2s .c om } 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. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null; try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { System.out.println(item.getFieldName()); System.out.println(item.getString()); // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. System.out.println("File field name: " + item.getFieldName()); uploadedFile = new File(destinationDir, item.getName()); item.write(uploadedFile); System.out.println("File written to: " + uploadedFile.getAbsolutePath()); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }
From source file:edu.isi.karma.util.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) { // Download the file to the upload file folder File destinationDir = new File(destinationDirString); logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath()); 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. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null;/*from w w w .j a v a 2 s. co m*/ try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. uploadedFile = new File(destinationDir, item.getName()); if (item instanceof DiskFileItem) { DiskFileItem t = (DiskFileItem) item; if (!t.getStoreLocation().renameTo(uploadedFile)) item.write(uploadedFile); } else item.write(uploadedFile); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }