List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:edu.ucla.loni.server.Upload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {/* w w w. ja v a2 s . c o m*/ @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); // Go through the items and get the root and package String rootPath = ""; String packageName = ""; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("root")) { rootPath = item.getString(); } else if (item.getFieldName().equals("packageName")) { packageName = item.getString(); } } } if (rootPath.equals("")) { res.getWriter().println("error :: Root directory has not been found."); return; } Directory root = Database.selectDirectory(rootPath); // Go through items and process urls and files for (FileItem item : items) { // Uploaded File if (item.isFormField() == false) { String filename = item.getName(); ; if (filename.equals("") == true) continue; try { InputStream in = item.getInputStream(); //determine if it is pipefile or zipfile //if it is pipefile => feed directly to writeFile function //otherwise, uncompresse it first and then one-by-one feed to writeFile if (filename.endsWith(".zip")) { ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); while (entry != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (baos != null) { byte[] arr = new byte[4096]; int index = 0; while ((index = zip.read(arr, 0, 4096)) != -1) { baos.write(arr, 0, index); } } InputStream is = new ByteArrayInputStream(baos.toByteArray()); writeFile(root, packageName, is); entry = zip.getNextEntry(); } zip.close(); } else { writeFile(root, packageName, in); } in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage()); } } // URLs if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false) { String urlListAsStr = item.getString(); String[] urlList = urlListAsStr.split("\n"); for (String urlStr : urlList) { try { URL url = new URL(urlStr); URLConnection urlc = url.openConnection(); InputStream in = urlc.getInputStream(); writeFile(root, packageName, in); in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + urlStr); return; } } } } } catch (Exception e) { res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage()); } } }
From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java
/** ********************************************************** * doPost()/*from w w w .j av a2 s. co m*/ ************************************************************ */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { /* disable security for caAdatper 4.3 release 03-31-2009 HttpSession session = req.getSession(false); if(session==null) { res.sendRedirect("/caAdapterWS/login.do"); return; } String user = (String) session.getAttribute("userid"); System.out.println(user); AbstractSecurityDAO abstractDao= DAOFactory.getDAO(); SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess(); Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1); System.out.println(perm); if (!perm.getCreate()){ System.out.println("No create Permission for user" + user); res.sendRedirect("/caAdapterWS/permissionmsg.do"); return; } */ String name = "EMPTY"; // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(req); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("MSName")) { MSName = item.getString(); path = System.getProperty("gov.nih.nci.caadapter.path"); if (path == null) path = ScenarioUtil.SCENARIO_HOME; File scnHome = new File(path); if (!scnHome.exists()) scnHome.mkdir(); path = path + "/"; System.out.println(path); boolean exists = (new File(path + MSName)).exists(); if (exists) { System.out.println("Scenario exists, overwriting ... ..."); String errMsg = "Scenario exists, not able to save:" + MSName; req.setAttribute("rtnMessage", errMsg); res.sendRedirect("/caAdapterWS/errormsg.do"); return; } else { boolean success = (new File(path + MSName)).mkdir(); if (!success) { System.out.println("New scenario, Creating ... ..."); } } } } else { System.out.println(item.getFieldName()); name = item.getFieldName(); String filePath = item.getName(); String fileName = extractOriginalFileName(filePath); System.out.println("AddNewScenario.doPost()..original file Name:" + fileName); if (fileName == null || fileName.equals("")) continue; String uploadedFilePath = path + MSName + "/" + fileName; System.out.println("AddNewScenario.doPost()...write data to file:" + uploadedFilePath); File uploadedFile = new File(uploadedFilePath); if (name.equals("mappingFileName")) { String uploadedMapBak = uploadedFilePath + ".bak"; //write bak of Mapping file item.write(new File(uploadedMapBak)); updateMapping(uploadedMapBak); } else item.write(uploadedFile); } } ScenarioUtil.addNewScenarioRegistration(MSName); res.sendRedirect("/caAdapterWS/success.do"); } catch (NullPointerException ne) { System.out.println("Error in doPost: " + ne); req.setAttribute("rtnMessage", ne.getMessage()); res.sendRedirect("/caAdapterWS/errormsg.do"); } catch (Exception e) { System.out.println("Error in doPost: " + e); req.setAttribute("rtnMessage", e.getMessage()); res.sendRedirect("/caAdapterWS/error.do"); } }
From source file:com.liteoc.bean.rule.FileUploadHelper.java
@SuppressWarnings("unchecked") private List<File> getFiles(HttpServletRequest request, ServletContext context, String dirToSaveUploadedFileIn) { List<File> files = new ArrayList<File>(); // FileCleaningTracker fileCleaningTracker = // FileCleanerCleanup.getFileCleaningTracker(context); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(getFileProperties().getFileSizeMax()); try {//from www. j ava2 s . c o m // Parse the request 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()) { request.setAttribute(item.getFieldName(), item.getString()); // DO NOTHING , THIS SHOULD NOT BE Handled here } else { getFileProperties().isValidExtension(item.getName()); files.add(processUploadedFile(item, dirToSaveUploadedFileIn)); } } return files; } catch (FileSizeLimitExceededException slee) { throw new OpenClinicaSystemException("exceeds_permitted_file_size", new Object[] { String.valueOf(getFileProperties().getFileSizeMaxInMb()) }, slee.getMessage()); } catch (FileUploadException fue) { throw new OpenClinicaSystemException("file_upload_error_occured", new Object[] { fue.getMessage() }, fue.getMessage()); } }
From source file:com.github.glue.mvc.RequestHandler.java
private void init() { try {/*w w w. j ava 2 s. c o m*/ if (isMultipartContent(request)) { FileItemFactory itemFactory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(itemFactory); List<FileItem> items = fileUpload.parseRequest(request); for (FileItem fileItem : items) { if (fileItem.isFormField()) { parameters.put(fileItem.getFieldName(), new String[] { fileItem.getString(definition.getCharset()) }); } else { parameters.put(fileItem.getFieldName(), fileItem); } } } else { Map<String, String[]> paramteters = request.getParameterMap(); for (Map.Entry<String, String[]> item : paramteters.entrySet()) { String[] vars = item.getValue(); if (vars != null) { for (int i = 0; i < vars.length; i++) { vars[i] = new String(vars[i].getBytes("ISO-8859-1"), definition.getCharset()); } } parameters.put(item.getKey(), vars); } } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:eionet.gdem.utils.MultipartFileUpload.java
/** * Constructor. Creates a new FileUploadAdapter object * @param uploadAtOnce Upload at once/*from w ww. j a va2 s . co m*/ */ public MultipartFileUpload(boolean uploadAtOnce) { // Create a factory for disk-based file items factory = new DiskFileItemFactory(); // Create a new file upload handler upload = new ServletFileUpload(factory); _params = new HashMap(); initEscapes(); this._uploadAtOnce = uploadAtOnce; }
From source file:AdminPackage.AdminAddProductController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w .java2s .c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HProductDao pDao = new HProductDao(); Product product = new Product(); Categories c = new Categories(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); switch (name) { case "productName": product.setProductName(value); break; case "productDesc": product.setProductDescription(value); break; case "productPrice": product.setProductPrice(Float.parseFloat(value)); break; case "productQuantityAvailable": product.setProductQuntityavailable(Integer.parseInt(value)); break; case "productQuantitySold": product.setProductQuntitysold(Integer.parseInt(value)); break; case "productCategory": c.setIdcategory(Integer.parseInt(value)); product.setCategories(c); break; } } else { if (!item.isFormField()) { item.write(new File("C:/images/" + item.getName())); product.setProductImg(item.getName()); } } } } catch (FileUploadException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } pDao.insert(product); /* PrintWriter out = response.getWriter(); out.write("Done");*/ response.sendRedirect("/WebProjectServletJsp/AdminProductController"); }
From source file:Com.Dispatcher.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww .ja v a2s . co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file; Boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); Integer visitCount = (Integer) session.getAttribute(visitCountKey); // Check if this is new comer on your web page. if (visitCount == null) { session.setAttribute(userIDKey, userID); } else { visitCount++; userID = (String) session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); 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(fileRepository)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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 String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file to server in "/uploads/{sessionID}/" String clientDataPath = getServletContext().getInitParameter("clientFolder"); // TODO clear the client folder here // FileUtils.deleteDirectory(new File("clientDataPath")); if (fileName.lastIndexOf("\\") >= 0) { File input = new File(clientDataPath + session.getId() + "/input/"); input.mkdirs(); File output = new File(clientDataPath + session.getId() + "/output/"); output.mkdirs(); session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/"); session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/"); file = new File( input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/"))); } else { File input = new File(clientDataPath + session.getId() + "/input/"); input.mkdirs(); File output = new File(clientDataPath + session.getId() + "/output/"); output.mkdirs(); session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/"); session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/"); file = new File( input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1)); } fi.write(file); } } } catch (Exception ex) { System.out.println("Failure: File Upload"); System.out.println(ex); //TODO show error page for website } System.out.println("file uploaded"); // TODO make the fileRepository Folder generic so it doesnt need to be changed // for each migration of the program to a different server File input = new File((String) session.getAttribute("inputFolder")); File output = new File((String) session.getAttribute("outputFolder")); File profile = new File(getServletContext().getInitParameter("profileFolder")); File hintsXML = new File(getServletContext().getInitParameter("hintsXML")); System.out.println("folders created"); Controller controller = new Controller(input, output, profile, hintsXML); HashMap initialArtifacts = controller.initialArtifacts(); session.setAttribute("Controller", controller); System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n" + "Awaiting user to update parameters to generate next generation of results.\n"); String json = new Gson().toJson(initialArtifacts); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }
From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java
/** * Handles the HTTP/*from w w w . j av a 2s .c om*/ * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { log("Content-Type: " + request.getContentType()); // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); /* * Set the file size limit in bytes. This should be set as an * initialization parameter */ diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB. // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { log("Could not parse request", ex); } ListIterator li = items.listIterator(); while (li.hasNext()) { FileItem fileItem = (FileItem) li.next(); if (fileItem.isFormField()) { if (debug) { processFormField(fileItem); } } else { writer.print(processUploadedFile(fileItem)); } } } if ("application/octet-stream".equals(request.getContentType())) { log("Content-Type: " + request.getContentType()); String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } }
From source file:com.jflyfox.modules.filemanager.FileManager.java
public FileManager(HttpServletRequest request) { // get document root like in php String documentRoot = PathKit.getWebRootPath() + "/"; // get uploaded file list FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from ww w. ja v a 2s . c o m*/ if (ServletFileUpload.isMultipartContent(request)) files = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } this.properties.put("Date Created", null); this.properties.put("Date Modified", null); this.properties.put("Height", null); this.properties.put("Width", null); this.properties.put("Size", null); if (getConfig("doc_root") != null) this.fileRoot = getConfig("doc_root"); else this.fileRoot = documentRoot; dateFormat = new SimpleDateFormat(getConfig("date")); this.setParams(); loadLanguageFile(); }
From source file:mx.edu.ittepic.proyectofinal.servlets.UploadFile.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from www .j a v a 2 s.c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // process only if it is multipart content if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); } } } catch (Exception e) { e.printStackTrace(); } } }