List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:eg.agrimarket.controller.SignUpController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .j ava 2 s . com*/ * @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 { CreditDao creditDao = new CreditDaoImpl(); try { boolean creditExist = false; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); HttpSession session = request.getSession(false); User user = new User(); Credit credit = new Credit(); UserDao userDaoImpl = new UserDaoImpl(); ArrayList<eg.agrimarket.model.dto.Interest> newInterests = new ArrayList<>(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { user.setImage(image); } System.out.println(user.getImage()); } else { switch (item.getFieldName()) { case "name": user.setUserName(item.getString()); break; case "mail": user.setEmail(item.getString()); break; case "password": user.setPassword(item.getString()); break; case "job": user.setJob(item.getString()); break; case "date": DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(item.getString(), formatter); user.setDOB(date); break; case "address": user.setAddress(item.getString()); break; case "credit": user.setCreditNumber(item.getString()); credit.setNumber(item.getString()); if (creditDao.checkCredit(credit)) {//credit number is exist is if (!(userDaoImpl.isCreditNumberAssigned(credit))) { creditExist = true; System.out.println("creditExist = true;"); } else { creditExist = false; System.out.println("creditExist = falsefalse;"); } } else { creditExist = false; System.out.println("creditExist=false;"); } break; default: eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest(); interest.setId(Integer.parseInt(item.getString())); interest.setName(item.getFieldName()); newInterests.add(interest); System.out.println(item.getFieldName() + " : " + item.getString()); } } } // check if user exist in Db if (creditExist) { user.setInterests(newInterests); UserDaoImpl userDao = new UserDaoImpl(); // userDao.signUp(user); session.setAttribute("user", user); System.out.println(user.getInterests()); System.out.println(user.getImage()); response.sendRedirect("index.jsp"); } else { response.sendRedirect("sign_up.jsp"); System.out.println("user didnt saved"); } } catch (FileUploadException ex) { Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aquest.emailmarketing.web.controllers.ImportController.java
/** * Import list./*from w w w.ja v a 2s. c o m*/ * * @param model the model * @param request the request * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception * @throws ParserConfigurationException the parser configuration exception * @throws TransformerException the transformer exception * @throws ServletException the servlet exception * @throws FileUploadException the file upload exception */ @RequestMapping(value = "/importList", method = RequestMethod.POST) public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException, ParserConfigurationException, TransformerException, ServletException, FileUploadException { List<String> copypaste = new ArrayList<String>(); String listfilename = ""; String separator = ""; String broadcast_id = ""; String old_broadcast_id = ""; String listType = ""; EmailListForm emailListForm = new EmailListForm(); InputStream fileContent = null; List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName.equals("listType")) { listType = fieldValue; System.out.println(listType); } else if (fieldName.equals("copypaste")) { for (String line : fieldValue.split("\\n")) { copypaste.add(line); System.out.println(line); } } else if (fieldName.equals("listfilename")) { listfilename = fieldValue; } else if (fieldName.equals("separator")) { separator = fieldValue; } else if (fieldName.equals("broadcast_id")) { broadcast_id = fieldValue; } else if (fieldName.equals("old_broadcast_id")) { old_broadcast_id = fieldValue; } } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fileName = FilenameUtils.getName(item.getName()); fileContent = item.getInputStream(); } System.out.println(listfilename); System.out.println(separator); } int importCount = 0; if (listType.equals("copy")) { if (!copypaste.isEmpty()) { List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } else { // sta ako je prazno } } if (listType.equals("fromfile")) { List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } System.out.println(broadcast_id); model.addAttribute("importCount", importCount); model.addAttribute("emailListForm", emailListForm); Broadcast broadcast = broadcastService.getBroadcast(broadcast_id); System.out.println("Old broadcast: " + old_broadcast_id); if (!old_broadcast_id.isEmpty()) { model.addAttribute("old_broadcast_id", old_broadcast_id); } String message = null; if (broadcast.getBcast_template_id() != null) { message = "template"; } model.addAttribute("message", message); model.addAttribute("broadcast_id", broadcast_id); return "importlistreport"; }
From source file:com.pagoadalabs.fileupload.controller.FileController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w.j a va 2s . 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 { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } 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("e://temp")); // 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(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); 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 if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java
/** * This API is used to get uploaded file and create directory for given path in parameter. * // w w w . j av a 2s .com * @param filePath {@link String} to create directory. * @return {@link ServletFileUpload} uploaded file. */ private ServletFileUpload getUploadedFile(final String filePath) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); final File exportTableFd = new File(filePath); if (!exportTableFd.exists()) { exportTableFd.mkdir(); } return upload; }
From source file:ManageViewerFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a 2s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //get the viewer files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String viewerid = request.getParameter("viewerid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getViewerFiles")) { //getting viewer files //first get the filenames in the directory. //I will get the list of files in this directory and send it String studyPath = getServletContext().getRealPath("/viewer/" + viewerid); File root = new File(studyPath); File[] list = root.listFiles(); ArrayList<String> fileItemList = new ArrayList<String>(); if (list == null) { System.out.println("List is null"); return; } for (File f : list) { if (f.isDirectory()) { ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName()); for (int i = 0; i < dirItems.size(); i++) { fileItemList.add(dirItems.get(i)); } } else { //System.out.println(f.getName()); fileItemList.add(f.getName()); } } System.out.println("**** Printing the fileItems now **** "); String outputStr = ""; for (int i = 0; i < fileItemList.size(); i++) { outputStr += fileItemList.get(i) + "::::"; } out.println(outputStr); } else if (command.equalsIgnoreCase("addViewerFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/viewer/" + viewerid); File studyFolder = new File(studyFolderPath); //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); int cnt = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { // cnt++; String name = new File(item.getName()).getName(); //write the file to disk if (!studyFolder.exists()) { studyFolder.mkdir(); System.out.println("The Folder has been created"); } item.write(new File(studyFolder + File.separator + name)); System.out.println("File name is :: " + name); } } out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteViewerFiles")) { //get the array of files and delete thems String[] mpk; //get the array of file-names mpk = request.getParameterValues("fileNames"); for (int i = 0; i < mpk.length; i++) { String filePath = getServletContext().getRealPath("/viewer/" + viewerid + "/" + mpk[i]); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:fi.helsinki.lib.simplerest.CommunityLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;//from w w w . ja v a 2 s.com Community community; try { c = getAuthenticatedContext(); community = Community.find(c, this.communityId); if (community == null) { return errorNotFound(c, "Could not find the community."); } } catch (SQLException e) { return errorInternal(c, e.toString()); } try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(logoRepresentation); if (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { InputStream inputStream = item.openStream(); community.setLogo(inputStream); Bitstream logo = community.getLogo(); BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType()); logo.setFormat(bf); logo.update(); community.update(); } } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Logo set."); }
From source file:Controllers.AddItem.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* ww w .java 2s. 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 { String name = null; String itemCode = null; String price = null; String quantity = null; String category = null; String image = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login"); return; } // request.getServletContext().getRealPath("/uploads"); String path = request.getServletContext().getRealPath("/uploads"); System.out.println(path); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); // new File(path).mkdirs(); File directory = new File(path + File.separator + fileName); image = fileName; item.write(directory); } else { if ("name".equals(item.getFieldName())) { name = item.getString(); } else if ("itemCode".equals(item.getFieldName())) { itemCode = item.getString(); } else if ("price".equals(item.getFieldName())) { price = item.getString(); } else if ("quantity".equals(item.getFieldName())) { quantity = item.getString(); } else if ("category".equals(item.getFieldName())) { category = item.getString(); } } } //File uploaded successfully System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user); String message; if (status) { message = "Item saved successfully"; response.sendRedirect("dashboard"); } else { message = "Item not saved !!"; request.setAttribute("message", message); request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response); } }
From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.java
/** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs *///w ww . j a v a 2 s.c o m public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Determine request by attributes String action = (String) request.getParameter("action"); String type = (String) request.getParameter("type"); System.out.println("(*) UploadServlet ...action " + action); if (action == null) { action = "upload_data"; } 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(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { /* * Parse the request */ List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString()); //String s = convertStreamToString(item.getInputStream(), item.getSize()); //System.out.println(s); } else { //Handle Uploaded files. System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); String s = convertStreamToString(item.getInputStream(), item.getSize()); //System.out.println(s); request.getSession().setAttribute("action", action); if (action.compareTo("upload_data") == 0) { request.getSession().setAttribute("codes", s); } else { Mapping mapping = new Mapping().toMapping(s); System.out.println("Mapping " + mapping.getMappingName() + " uploaded."); System.out.println("Mapping version: " + mapping.getMappingVersion()); MappingObject obj = mapping.toMappingObject(); HashMap mappings = (HashMap) request.getSession().getAttribute("mappings"); if (mappings == null) { mappings = new HashMap(); } mappings.put(obj.getKey(), obj); request.getSession().setAttribute("mappings", mappings); } } } } catch (FileUploadException ex) { log("Error encountered while parsing the request", ex); } catch (Exception ex) { log("Error encountered while uploading file", ex); } //long ms = System.currentTimeMillis(); if (action.compareTo("upload_data") == 0) { if (type.compareTo("codingscheme") == 0) { response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/pages/codingscheme_data.jsf")); } else if (type.compareTo("ncimeta") == 0) { response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/pages/ncimeta_data.jsf")); } else if (type.compareTo("valueset") == 0) { response.sendRedirect( response.encodeRedirectURL(request.getContextPath() + "/pages/valueset_data.jsf")); } } else { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/pages/home.jsf")); } }
From source file:Control.Upload.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w. j ava 2 s .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 { int k = 0; String userid = null; ArrayList<String> nameImage = new ArrayList<String>(); String album = null; ArrayList<String> typeImage = new ArrayList<String>(); ArrayList<Integer> priceImage = new ArrayList<Integer>(); String tempPath = "/temp"; String absoluteTempPath = this.getServletContext().getRealPath(tempPath); if (absoluteTempPath == null) { String serverContext = this.getServletContext().getRealPath("/"); String createPath = serverContext + "temp"; File tempfolder = new File(createPath); tempfolder.mkdir(); absoluteTempPath = this.getServletContext().getRealPath(tempPath); } String absoluteFilePath = this.getServletContext().getRealPath("/data/Image"); int maxFileSize = 50 * 1024; int maxMemSize = 4 * 1024; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); File file = new File(absoluteTempPath); factory.setRepository(file); ServletFileUpload upload = new ServletFileUpload(factory); //upload.setProgressListener(new MyProgressListener(out)); List<FileItem> items = upload.parseRequest(request); if (items.size() > 0) { for (int i = items.size() - 1; i >= 0; i--) { if (items.get(i).isFormField()) { if (null != items.get(i).getFieldName()) switch (items.get(i).getFieldName()) { case "userid": userid = items.get(i).getString(); break; case "nameImageUpload": nameImage.add(items.get(i).getString()); break; case "albumUpload": album = items.get(i).getString(); break; case "typeImageUpload": typeImage.add(items.get(i).getString()); break; case "priceImageUpload": priceImage.add(parseInt(items.get(i).getString())); break; default: break; } } else if ("images".equals(items.get(i).getFieldName())) { if (!"".equals(items.get(i).getName()) && !items.get(i).getName().isEmpty()) { String extension = null; String newLink; Integer newIntIdImage = Image.listImg.size() + k; String newIdImage = newIntIdImage.toString(); if (items.get(i).getName().endsWith("jpg")) { newLink = "/Image/" + newIdImage + ".jpg"; file = new File(absoluteFilePath + "//" + newIdImage + ".jpg"); } else if (items.get(i).getName().endsWith("JPG")) { newLink = "/Image/" + newIdImage + ".jpg"; file = new File(absoluteFilePath + "//" + newIdImage + ".jpg"); } else if (items.get(i).getName().endsWith("png")) { newLink = "/Image/" + newIdImage + ".png"; file = new File(absoluteFilePath + "//" + newIdImage + ".png"); } else if (items.get(i).getName().endsWith("PNG")) { newLink = "/Image/" + newIdImage + ".png"; file = new File(absoluteFilePath + "//" + newIdImage + ".png"); } else { return; } boolean check = Image_DAL.addImage(newLink, userid, album, nameImage.get(0), typeImage.get(0), priceImage.get(0)); nameImage.remove(0); typeImage.remove(0); priceImage.remove(0); if (check) { items.get(i).write(file); k++; } } } else { } } request.setAttribute("user", userid); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index"); dispatcher.forward(request, response); return; } for (int i = items.size() - 1; i >= 0; i--) if (items.get(i).isFormField()) if ("userid".equals(items.get(i).getFieldName())) userid = items.get(i).getString(); request.setAttribute("error", "No file upload"); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index"); dispatcher.forward(request, response); } catch (Exception ex) { System.err.println(ex); } }
From source file:cdc.util.Upload.java
public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { int cont = 0; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = null; try {/*from w w w .j a v a 2 s . co m*/ fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } String optionalFileName = ""; FileItem fileItem = null; Iterator it = fileItemsList.iterator(); do { //cont++; FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { if (fileItemTemp.getFieldName().equals("file")) { optionalFileName = fileItemTemp.getString(); } } else { fileItem = fileItemTemp; } if (cont != (fileItemsList.size())) { if (fileItem != null) { String fileName = fileItem.getName(); if (fileItem.getSize() > 0) { if (optionalFileName.trim().equals("")) { fileName = FilenameUtils.getName(fileName); } else { fileName = optionalFileName; } String dirName = request.getServletContext().getRealPath(pasta); File saveTo = new File(dirName + fileName); //System.out.println("caminho: " + saveTo.toString() ); try { fileItem.write(saveTo); } catch (Exception e) { } } } } cont++; } while (it.hasNext()); return true; } else { return false; } }