List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.esteban.cmms.maven.controller.Imagenes_Controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va 2 s .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 { String btne = request.getParameter("btn"); if (btne == null) { try { HttpSession sesion = request.getSession(); sesion.removeAttribute("imagenes"); Usuarios user = (Usuarios) sesion.getAttribute("usuario"); FileItemFactory itemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(itemFactory); String btn = null; Maquinas m = new Maquinas(); List<FileItem> items = upload.parseRequest(request); Imagenes pojo = new Imagenes(); pojo.setUserAction(user.getNombre()); for (FileItem item : items) { if (!item.isFormField()) { String contentType = item.getContentType(); if (!contentType.equals("image/png")) { //|| !contentType.equals("image/jpg") continue; } File img = new File( "/home/esteban/NetBeansProjects/" + "CMMS-Maven/src/main/webapp/Imagenes/images_cli", new Date() + item.getName()); item.write(img); pojo.setImagen(img.getName()); } if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("maquina")) { int idm = Integer.parseInt(item.getString()); System.out.println("Maquina"); m.setId(idm); pojo.setMaquinas(m); } else if (item.getFieldName().equalsIgnoreCase("btn")) { System.out.println("Guardar cambios"); btn = item.getString().replaceAll("\\s", ""); } else if (item.getFieldName().equalsIgnoreCase("id")) { System.out.println("id imagen"); pojo.setId(Integer.parseInt(item.getString())); } } } pojo.setEstado("Activo"); System.out.println("ste es el boton" + btn); if (btn.equalsIgnoreCase("actualizar")) { new Imagenes_Model().updateImagen(pojo); } else { new Imagenes_Model().addImagen(pojo); } response.sendRedirect("Imagenes"); } catch (FileUploadException ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } } else { String btn = btne.replaceAll("\\s", ""); if (btn.equalsIgnoreCase("imagenes")) { Imagenes_Model model = new Imagenes_Model(); HttpSession sesion = request.getSession(); String valor = request.getParameter("valor"); List<Imagenes> result = new ArrayList<Imagenes>(); if (valor.equalsIgnoreCase("activo")) { try { result = model.getAllImagenes(); sesion.setAttribute("imagenes", result); sesion.setAttribute("maquinas", new Maquinas_Model().getAllMaquinas()); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes"); } else if (valor.equalsIgnoreCase("inactivo")) { try { result = model.listNoActive(); sesion.setAttribute("imagenes", result); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes/archivados.jsp"); } } else if (btn.equalsIgnoreCase("estado")) { System.out.println("Definicin de estado"); System.out.println("Nuevo estado: " + request.getParameter("estado")); Usuarios user = (Usuarios) request.getSession().getAttribute("usuario"); try { new Imagenes_Model().estadoImagen(request.getParameter("estado"), Integer.parseInt(request.getParameter("id")), user.getNombre()); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } System.out.println("Estado definido con xito"); response.sendRedirect("Imagenes"); } } }
From source file:ManageDatasetFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a 2 s . c om*/ * * @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 dataset files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String datasetid = request.getParameter("datasetid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getDatasetFiles")) { //getting dataset files //first get the filenames in the directory. //I will get the list of files in this directory and send it String datasetPath = getServletContext().getRealPath("/datasets/" + datasetid); System.out.println(datasetid); File root = new File(datasetPath); 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); } if (outputStr.length() > 1) { out.println(outputStr); } } else if (command.equalsIgnoreCase("addDatasetFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/datasets/" + datasetid); 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); } } System.out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); System.out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); System.out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteDatasetFiles")) { //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("/datasets/" + datasetid + "/" + mpk[i]); System.out.println(filePath); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:com.auction.servlet.FileUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j a v a2 s .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 IOException { response.setContentType("text/html;charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin", "*"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { String randomFileName = StringUtils.getRandomString() + ".jpg"; List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { //String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); if (!path.exists()) { boolean status = path.mkdirs(); } //File uploadedFile = new File(path + "/" + fileName); File uploadedFile = new File(path + "/" + randomFileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } out.print(randomFileName); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:Controller.ControllerProducts.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .jav a 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 { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path" + fileName); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; System.out.println("Rpath" + RealPath); File savedFile = new File(RealPath); item.write(savedFile); //System.out.println("upload\\"+fileName); //insert Product String code = (String) params.get("txtcode"); String name = (String) params.get("txtname"); String price = (String) params.get("txtprice"); Products sp = new Products(); sp.InsertProduct(code, name, price, "upload\\" + fileName); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } //this.processRequest(request, response); }
From source file:gwtuploadsample.server.SampleUploadServlet.java
/** * Override executeAction to save the received files in a custom place * and delete this items from session.// w w w . ja va 2 s . c o m */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { /// Create a new file based on the remote file name in the client // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // File file =new File("/tmp/" + saveName); /// Create a temporary file placed in /tmp (only works in unix) // File file = File.createTempFile("upload-", ".bin", new File("/tmp")); /// Create a temporary file placed in the default system temp folder File file = File.createTempFile("upload-", ".bin"); item.write(file); /// Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); /// Compose a xml message with the full file information response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n"; } catch (Exception e) { throw new UploadActionException(e); } } } /// Remove files from session because we have a copy of them removeSessionFileItems(request); /// Send information of the received files to the client. return "<response>\n" + response + "</response>\n"; }
From source file:controller.Upload.java
/** * Servlet implementation class UploadServlet *//*from w w w.jav a2 s . com*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // constructs the folder where uploaded file will be stored String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); String fileName = "", newname = ""; try { // Parse the request List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { // fileName = (String)session.getId() + new File(item.getName()).getName(); // String filePath = uploadFolder + File.separator + fileName; fileName = new File(item.getName()).getName(); newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf(".")); String filePath = uploadFolder + File.separator + newname; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory item.write(uploadedFile); } } userDao ud = new userDao(); ud.changeuserpic((int) session.getAttribute("userID"), newname); // displays done.jsp page after upload finished getServletContext().getRequestDispatcher("/done.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.amalto.core.servlet.UploadFile.java
private File writeJobFile(FileItem item, String filename, String context) throws Exception { File file;/* www . j av a 2 s .com*/ if (item.getName().endsWith(".zip")) { //$NON-NLS-1$ String dir = JobContainer.getUniqueInstance().getDeployDir(); file = new File(dir + File.separator + filename); // better handle concurrent file system modifications // see com.amalto.core.jobox.watch.JoboxListener.fileChanged(List<String>, List<String>, // List<String>) try { if (LOG.isDebugEnabled()) { LOG.debug("Deleting file '" + file.getAbsolutePath() + "'"); //$NON-NLS-1$//$NON-NLS-2$ } item.write(file); JobContainer jobContainer = JobContainer.getUniqueInstance(); jobContainer.setContextStrToBeSaved(file.getAbsolutePath(), context); } catch (EOFException e) { LOG.warn("Attempted to to update job '" + item.getName() //$NON-NLS-1$ + "' but is being modified by concurrent process."); //$NON-NLS-1$ } catch (ZipException e) { LOG.warn("Attempted to to update job '" + item.getName() //$NON-NLS-1$ + "' but is being modified by concurrent process."); //$NON-NLS-1$ } } else if (item.getName().endsWith(".war")) { //$NON-NLS-1$ file = new File(containerWebAppsPath + File.separator + filename); if (LOG.isDebugEnabled()) { LOG.debug("Writing file '" + file.getAbsolutePath() + "'"); //$NON-NLS-1$//$NON-NLS-2$ } item.write(file); } else { throw new IllegalArgumentException("Unknown job deployment for file '" + filename + "'"); //$NON-NLS-1$//$NON-NLS-2$ } return file; }
From source file:hd.controller.AddImageToIdeaBookServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww . j av a 2 s.c om*/ * * @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 { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } String ideaBookIdTemp = (String) params.get("txtIdeabookId"); int ideaBookId = Integer.parseInt(ideaBookIdTemp); IdeaBookDAO ideabookDao = new IdeaBookDAO(); String tilte = (String) params.get("newGalleryName"); String description = (String) params.get("GalleryDescription"); String url = "images/" + fileName; IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO(); IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId); HDSystem system = new HDSystem(); system.setNotificationIdeaBook(request); response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:controllers.IndexController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView uploadpic(HttpServletRequest request, ModelAndView model) { String path = request.getRealPath("/upload_images"); path = path.substring(0, path.indexOf("\\mavenproject1")); path = path + "\\mavenproject1\\mavenproject1\\src\\main\\webapp\\upload_images"; DiskFileItemFactory dfif = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(dfif); try {/*from w w w. jav a 2 s.co m*/ List<FileItem> fit = uploader.parseRequest(request); for (FileItem fileItem : fit) { try { contenttype = fileItem.getContentType(); contenttype = contenttype.substring(6, contenttype.length()); if (fileItem.isFormField() == false && contenttype.equals("jpeg") || contenttype.equals("png")) { file = new File(path + "/" + fileItem.getName()); fileItem.write(file); } } catch (Exception ey) { } } return model; } catch (Exception ex) { if (file.exists()) { file.delete(); } model.addObject("errorcode", ex.toString()); model.setViewName("nosuccessform"); return model; } }
From source file:com.github.ikidou.handler.FormHandler.java
private List<FileEntity> getFileEntities(Map<String, Object> result, List<FileItem> fileItems) throws Exception { List<FileEntity> fileEntities = new ArrayList<>(); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { fileItem.getFieldName();/* ww w .ja va 2 s . c om*/ result.put(fileItem.getFieldName(), fileItem.getString()); if (!fileItem.isInMemory()) { fileItem.delete(); } } else { FileEntity fileEntity = new FileEntity(); fileEntity.name = fileItem.getName(); fileEntity.contentType = fileItem.getContentType(); fileEntity.size = fileItem.getSize(); fileEntity.readableSize = FileSizeUtil.toReadable(fileItem.getSize()); fileEntity.savePath = "Data/" + fileEntity.name; File file = new File(fileEntity.savePath); fileItem.write(file); fileEntities.add(fileEntity); } } return fileEntities; }