List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:br.com.bluesoft.pronto.controller.TicketController.java
@SuppressWarnings("unchecked") @RequestMapping("/ticket/upload.action") public String upload(final HttpServletRequest request, final int ticketKey) throws Exception { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); final List<FileItem> items = upload.parseRequest(request); final String ticketDir = Config.getImagesFolder() + ticketKey + "/"; final File dir = new File(ticketDir); dir.mkdirs();//from w w w . j ava 2 s. c o m for (final FileItem fileItem : items) { final String nomeDoArquivo = fileItem.getName().toLowerCase().replace(' ', '_') .replaceAll("[^A-Za-z0-9._\\-]", ""); fileItem.write(new File(ticketDir + nomeDoArquivo)); } return "redirect:editar.action?ticketKey=" + ticketKey; }
From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.AdminProperties.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart; String filePath;/*ww w . j av a2s .c o m*/ int maxFileSize = 9000 * 1024; int maxMemSize = 4 * 1024; File file; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); boolean small = request.getParameter("size").equals("small"); String message; 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(this.getServletContext().getRealPath("/") + "img/")); // 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<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { // Get the uploaded file parameters String contentType = fileItem.getContentType(); if (contentType.equals("image/png")) { String fileName; if (small) { fileName = "logo_small.png"; } else { fileName = "logo.png"; } filePath = this.getServletContext().getRealPath("/") + "img/" + fileName; // Write the file file = new File(filePath); fileItem.write(file); } else { throw new Exception("type"); } } } message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">" + "<div class=\"callout success\">" + "<h5>Logo uploaded successfully</h5>" + "</div>" + "</div>" + "</div>" + "</div>"; request.setAttribute("msg", message); } catch (Exception ex) { if (ex.getMessage().equals("type")) { message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">" + "<div class=\"callout alert\">" + "<h5>Wrong Type</h5>" + "<p>Please upload a PNG image</p>" + "</div>" + "</div>" + "</div>" + "</div>"; } else { message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">" + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div>" + "</div>" + "</div>" + "</div>"; } request.setAttribute("msg", message); } doGet(request, response); }
From source file:com.intranet.intr.contabilidad.EmpControllerFacturaCompra.java
@RequestMapping(value = "EaddFacturaCompraRF.htm", method = RequestMethod.POST) public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {/* w w w . jav a 2s . c o m*/ String mensaje = ""; String ruta = "redirect:ECompra.htm"; compraR gr = new compraR(); //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (idPC != 0) { gr.setIdcompra(idPC); if (compraRService.existe(item.getName()) == false) { System.out.println("NOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); compraRService.insertar(gr); } } else ruta = "redirect:ECompra.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:com.wakasta.tubes2.AddProductPost.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String item_data = ""; // 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;// w ww . j av a2s .c o m } 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("c:\\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)); } item_data = Base64.encodeBase64String(fi.get()); fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); // out.println(file); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } catch (java.lang.Exception ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.controller.RecipeImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*ww w .ja v a 2 s . co 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"); //retrieving the path to store image from web.xml filePath = getServletContext().getInitParameter("recipeImageStorePath"); //retrieving the path to display image from web.xml fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath"); // 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("c:\\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>"); out.println("1"); while (i.hasNext()) { out.println("2"); FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); fileName = randomString(fileName); 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>" + filePath); } else { out.println("No file"); } } out.println("</body>"); out.println("</html>"); RecipeBean recipeBean = new RecipeBean(); RecipeDAO recipeDAO = new RecipeDAO(); String image = fileDisplay + "" + fileName; out.println(image); HttpSession session = request.getSession(); String recipeId = (String) session.getAttribute("recipeId"); session.removeAttribute("recipeId"); recipeDAO.addImage(recipeId, image); response.sendRedirect("Home"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.aes.controller.EmpireController.java
@RequestMapping(value = "addpresentation", method = RequestMethod.POST) public String doAction5(HttpServletRequest request, HttpServletResponse response, @ModelAttribute Chapter chapter, @ModelAttribute UserDetails loggedUser, BindingResult result, Map<String, Object> map) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); Presentation tempPresentation = new Presentation(); String chapterId = ""; String description = ""; try {//from ww w .j a va2 s. c o m @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = context.getRealPath("") + File.separator + "uploads" + File.separator + fileName; File storeFile = new File(filePath); item.write(storeFile); tempPresentation.setFilePath(filePath); tempPresentation.setFileSize(item.getSize()); tempPresentation.setFileType(item.getContentType()); tempPresentation.setFileName(fileName); } else { String name = item.getFieldName(); String value = item.getString(); if (name.equals("chapterId")) { chapterId = value; } else { description = value; } } } } } catch (Exception ex) { ex.printStackTrace(); } tempPresentation.setRecordStatus(true); tempPresentation.setDescription(description); int id = Integer.parseInt(chapterId); tempPresentation.setChapter(this.service.getChapterById(id)); service.addPresentation(tempPresentation); map.put("tempPresentation", new Presentation()); map.put("chapterId", chapterId); map.put("presentations", service.getAllPresentationsByChapterId(Integer.parseInt(chapterId))); return "../../admin/add_presentation"; }
From source file:com.antinymail.ventadecasas.servlet.UploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.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;/* w w w. j a va2 s .co m*/ } 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("c:\\temp")); //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); factory.setRepository( new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo")); //factory.setRepository(new Uri()); // 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("\\"))); //file = new File( fileName); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); //file = new File( fileName); } fi.write(file); //fi.write( fileNa ) ; out.println("Uploaded Filename: " + fileName + "<br>"); out.println("La ruta inicial era: " + filePath + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:it.unisa.tirocinio.servlet.UploadInformationForModuleFilesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . 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, JSONException { try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); AdministratorDBOperation getSerialNumberObj = new AdministratorDBOperation(); ConcreteStaff aAdmin = null; String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String adminSubfolderPath = filePath; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); DateFormat dateFormat = new SimpleDateFormat("yyyy"); Date date = new Date(); if (fieldName.equals("modulefile")) { fileToStore = new File( adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Module.pdf"); } else if (fieldName.equals("registerfile")) { fileToStore = new File( adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Register.pdf"); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); aAdmin = getSerialNumberObj.getFK_DepartimentbyFK_Account(Integer.parseInt(fi.getString())); serialNumber = "" + aAdmin.getFKDepartment(); adminSubfolderPath += fileSeparator + serialNumber; new File(adminSubfolderPath).mkdir(); } } message.put("status", 1); out.print(message.toString()); } catch (IOException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (FileUploadException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:com.skin.taurus.http.servlet.UploadServlet.java
/** * @param item/*from ww w . ja v a2s .c o m*/ * @throws Exception */ private String save(FileItem item) throws Exception { String fileName = this.getFileName(item.getName()); String extension = this.getFileExtensionName(fileName); if (logger.isDebugEnabled()) { logger.debug("Client File: " + item.getName()); logger.debug("ContentType: " + item.getContentType()); logger.debug("Field Name : " + item.getFieldName()); logger.debug("File Name : " + fileName); logger.debug("Extension : " + extension); } int i = 1; String shortName = fileName.substring(0, fileName.length() - extension.length()); File file = null; do { file = new File("./upload/" + shortName + "_" + (i) + extension); i++; } while (file.exists()); if (logger.isDebugEnabled()) { logger.debug("Save " + fileName + " To " + file.getAbsolutePath()); } item.write(file); return file.getCanonicalPath(); }
From source file:edu.iastate.airl.semtus.server.UploadServiceController.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // process only multipart requests 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); // Parse the request try {//from w w w. j a va2 s . com List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) continue; String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName); // first clean-up the folder; we want no clutter on the server :-) String[] ls = new File(Utils.UPLOAD_DIRECTORY).list(); for (int idx = 0; idx < ls.length; idx++) { File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]); file.delete(); } if (uploadedFile.createNewFile()) { item.write(uploadedFile); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().print("The file was created successfully."); resp.flushBuffer(); } else { throw new IOException("The file already exists in repository."); } } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while creating the file : " + e.getMessage()); } } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }