List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:com.openhr.company.UploadCompLicenseFile.java
@Override public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();//from w ww . j a v a2 s. co m return map.findForward("HRHome"); } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); // Read the file object contents and parse it and store it in the repos FileInputStream fstream = new FileInputStream(storeFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { System.out.print("Processing line - " + strLine); String[] lineColumns = strLine.split(COMMA); if (lineColumns.length < 8) { br.close(); in.close(); fstream.close(); throw new Exception("The required columns are missing in the line - " + strLine); } // Format is - CompID,CompName,Branch,Address,From,To,LicenseKey,FinStartMonth String companyId = lineColumns[0]; String companyName = lineColumns[1]; String branchName = lineColumns[2]; String address = lineColumns[3]; String fromDateStr = lineColumns[4]; String toDateStr = lineColumns[5]; String licenseKey = lineColumns[6]; String finStartMonthStr = lineColumns[7]; Date fromDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH) .parse(fromDateStr); Date toDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH).parse(toDateStr); address = address.replace(";", ","); List<Company> eComp = CompanyFactory.findByName(companyName); if (eComp == null || eComp.isEmpty()) { Company company = new Company(); company.setCompanyId(companyId); company.setName(companyName); company.setFystart(Integer.parseInt(finStartMonthStr)); Branch branch = new Branch(); branch.setAddress(address); branch.setCompanyId(company); branch.setName(branchName); Licenses license = new Licenses(); license.setActive(1); license.setCompanyId(company); license.setFromdate(fromDate); license.setTodate(toDate); license.formLicenseKey(); System.out.println("License key formed - " + license.getLicensekey()); System.out.println("License key given - " + licenseKey); if (license.getLicensekey().equalsIgnoreCase(licenseKey)) { CompanyFactory.insert(company); BranchFactory.insert(branch); LicenseFactory.insert(license); } else { br.close(); in.close(); fstream.close(); throw new Exception("License is tampared. Contact Support."); } } else { // Company is present, so update it. Company company = eComp.get(0); List<Licenses> licenses = LicenseFactory.findByCompanyId(company.getId()); Licenses newLicense = new Licenses(); newLicense.setActive(1); newLicense.setCompanyId(company); newLicense.setFromdate(fromDate); newLicense.setTodate(toDate); newLicense.formLicenseKey(); System.out.println("License key formed - " + newLicense.getLicensekey()); System.out.println("License key given - " + licenseKey); if (newLicense.getLicensekey().equalsIgnoreCase(licenseKey)) { for (Licenses lic : licenses) { if (lic.getActive().compareTo(1) == 0) { lic.setActive(0); LicenseFactory.update(lic); } } LicenseFactory.insert(newLicense); } else { br.close(); in.close(); fstream.close(); throw new Exception("License is tampared. Contact Support."); } } } //Close the input stream br.close(); in.close(); fstream.close(); } } System.out.println("Upload has been done successfully!"); } catch (Exception ex) { System.out.println("There was an error: " + ex.getMessage()); ex.printStackTrace(); } return map.findForward("CompLicHome"); }
From source file:com.controller.changeLogo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. j a va2 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 */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); getSqlMethodsInstance().session = request.getSession(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, uploadType = null; RequestDispatcher request_dispatcher = null; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.USER_LOGO; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { fieldName = fi.getFieldName(); if (fieldName.equals("upload")) { uploadType = fi.getString(); } } else { // Get the uploaded file parameters fieldName = fi.getFieldName(); fileName = fi.getName(); Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID"); uploadPath = uploadPath + File.separator + UID + File.separator + "logo"; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = Str + "_" + UID + ".jpeg"; fileName = fileName + "_" + UID; getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); if (uploadType.equals("update")) { String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID); String filePath_to_delete = uploadPath + File.separator + file_name_to_delete; File deletefile = new File(filePath_to_delete); deletefile.delete(); } filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); getSqlMethodsInstance().updateUsers(UID, fileName); out.println("Uploaded Filename: " + filePath + "<br>"); response.sendRedirect(request.getContextPath() + "/settings.jsp"); } } } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); getSqlMethodsInstance().closeConnection(); } }
From source file:controller.insertProduct.java
private void insertProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String productType = null;/*from w ww . ja v a2s . c o m*/ String resolution = null; String hdmi = null; String usb = null; String model = null; String size = null; String warranty = null; String productName = null; int price = 0; String description = null; Integer quantity = null; String produceID = null; String image = null; String uploadDirectory = "/Product/Images"; 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); File uploadDir; File storeFile; try { @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 = uploadDirectory + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); image = produceID + "/" + fileName; System.out.println(storeFile.getPath()); } else { switch (item.getFieldName()) { case "productName": productName = item.getString("UTF-8"); break; case "produceID": { produceID = item.getString("UTF-8"); uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID); if (!uploadDir.exists()) { uploadDir.mkdir(); } uploadDirectory = uploadPath + uploadDirectory + "/" + produceID; break; } case "price": price = (Integer.parseInt(item.getString("UTF-8"))); break; case "quantity": quantity = (Integer.parseInt(item.getString("UTF-8"))); break; case "productType": productType = item.getString("UTF-8"); break; case "resolution": resolution = item.getString("UTF-8"); break; case "hdmi": hdmi = item.getString("UTF-8"); break; case "usb": usb = item.getString("UTF-8"); break; case "Model": model = item.getString("UTF-8"); break; case "size": size = item.getString("UTF-8"); break; case "warranty": warranty = item.getString("UTF-8"); break; case "description": { description = item.getString("UTF-8"); System.out.println(description); break; } } } } } } catch (Exception ex) { System.out.println(ex); } @SuppressWarnings("null") ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty); Products product = new Products(productName, price, description, quantity, image, prinfo, produceID); if (ProductsDAO.insertProduct(product)) { out.print( "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } else { out.print( "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } }
From source file:it.fub.jardin.server.Upload.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) /* throws ServletException, IOException */ { try {//from w ww. java2 s . c o m this.dbProperties = new DbProperties(); } catch (VisibleException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.dbConnectionHandler = this.dbProperties.getConnectionHandler(); try { this.dbUtils = new DbUtils(dbProperties, dbConnectionHandler); } catch (VisibleException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.mailUtility = new MailUtility(dbConnectionHandler.getDbConnectionParameters().getMailSmtpHost(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpAuth(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpUser(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpPass(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpSender(), dbConnectionHandler.getDbConnectionParameters().getMailSmtpSysadmin()); subSystem = dbConnectionHandler.getDbConnectionParameters().getSubSystem(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_SIZE); String m = null; try { // 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()) { this.processFormField(item); } else { m = this.processUploadedFile(item); } } response.setContentType("text/plain"); response.getWriter().write(m); } catch (Exception e) { // Log.warn("Errore durante l'upload del file", e); } }
From source file:controlador.SerCandidato.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //ruta relativa en donde se guardan las fotos de candidatos String ruta = getServletContext().getRealPath("/") + "images/files/candidatos/"; //Partido p = new Partido(); Candidato c = new Candidato(); int accion = 1; //1=gregar 2=modificar if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); File repositoryPath = new File("/temp"); diskFileItemFactory.setRepository(repositoryPath); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setSizeMax(81920); // bytes upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb List listUploadFiles = null; FileItem item = null;/*from www . ja v a2s. co m*/ try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String tipo = item.getContentType(); long tamanio = item.getSize(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(ruta, nombre); item.write(archivo); if (archivo.exists()) { c.setFoto(nombre); } else { out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>"); } } } else { //se reciben los campos de texto enviados y se igualan a los atributos del objeto if (item.getFieldName().equals("slPartido")) { c.setIdPartido(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("slDepartamento")) { c.setIdDepartamento(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("txtDui")) { c.setNumDui(item.getString()); } if (item.getFieldName().equals("txtId")) { c.setIdCandidato(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("txtTipo")) { //definimos que el candidato es tipo 1 (Partidario) c.setTipo(Integer.parseInt(item.getString())); } } } //si no se selecciono una imagen distinta, se conserva la imagen anterior if (c.getFoto() == null) { c.setFoto(CandidatoDTO.mostrarCandidato(c.getIdCandidato()).getFoto()); } //cuando se presiona el boton de agregar if (c.getIdCandidato() == 0) { if (CandidatoDTO.agregarCandidato(c)) { //candidato partidario = 1 //candidato independiente = 2 if (c.getTipo() == 1) { //crud de canidatos partidadios response.sendRedirect(this.redireccionJSP); } else { //crud de canidatos independientes response.sendRedirect(this.redireccionJSP2); } } else { //cambiar por alguna accion en caso de error out.print("Error al insertar"); } } //cuando se presiona el boton de modificar else { if (CandidatoDTO.modificarCandidato(c)) { if (c.getTipo() == 1) { //crud de canidatos partidadios response.sendRedirect(this.redireccionJSP); } else { //crud de canidatos independientes response.sendRedirect(this.redireccionJSP2); } } else { out.print("Error al modificar"); } } } catch (FileUploadException e) { out.println("Error Upload: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { out.println("Error otros: " + e.getMessage()); e.printStackTrace(); } } }
From source file:com.javaweb.controller.ThemTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from www . ja v a2 s . co m*/ * @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, ParseException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); // session.removeAttribute("errorreg"); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 0; TintucService tintucservice = new TintucService(); //File upload String folderupload = getServletContext().getInitParameter("file-upload"); String rootPath = getServletContext().getRealPath("/"); filePath = rootPath + folderupload; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); 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:\\Windows\\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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); //change file name fileName = FileService.ChangeFileName(fileName); // 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>"); } if (fi.isFormField()) { if (fi.getFieldName().equalsIgnoreCase("TieuDe")) { TieuDe = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) { NoiDung = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) { ngaydang = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) { GhiChu = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) { idloaitin = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) { idTK = Integer.parseInt(fi.getString("UTF-8")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu); boolean rs = tintucservice.InsertTintuc(tintuc); if (rs) { session.setAttribute("kiemtra", "1"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } else { session.setAttribute("kiemtra", "0"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } // try (PrintWriter out = response.getWriter()) { // /* TODO output your page here. You may use following sample code. */ // out.println("<!DOCTYPE html>"); // out.println("<html>"); // out.println("<head>"); // out.println("<title>Servlet ThemTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w .ja 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 */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BRAND_IMAGES_HOME; deletePath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("brandname")) { brandname = fi.getString(); } if (fieldName.equals("brandid")) { brandid = fi.getString(); } if (fieldName.equals("look")) { lookid = fi.getString(); } file_name_to_delete = brand.getFileName(Integer.parseInt(brandid)); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = brandname + "_" + Str + ".jpeg"; fileName = brandname + "_" + fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); out.println("</body>"); out.println("</html>"); } else { 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>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { out.close(); } }
From source file:admin.controller.ServletUpdateFonts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww. j av a 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 */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = ""; RequestDispatcher request_dispatcher; String fontname = null, fontid = null, lookid; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH; deletePath = AppConstants.BASE_FONT_UPLOAD_PATH; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("fontname")) { fontname = fi.getString(); } if (fieldName.equals("fontid")) { fontid = fi.getString(); file_name_to_delete = font.getFileName(Integer.parseInt(fontid)); } } else { fieldName = fi.getFieldName(); fileName = fi.getName(); if (fileName != "") { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } } font.changeFont(Integer.parseInt(fontid), fontname, fileName); response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp"); out.println("</body>"); out.println("</html>"); } else { 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>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception while Updating fonts", ex); } finally { try { out.close(); } catch (Exception e) { } } }
From source file:application.controllers.admin.EmotionList.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //upload image to browser for add emotions //upload image to browser for add emotions if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();//from ww w. jav a 2 s . c o m return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE); upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE); // constructs the directory path to store upload file // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY; String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } //list image user upload String[] arrLinkImage = null; try { int indexImage = 0; // parses the request's content to extract file data List formItems = upload.parseRequest(request); arrLinkImage = new String[formItems.size()]; Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String extensionImage = ""; for (int i = fileName.length() - 1; i >= 0; i--) { if (fileName.charAt(i) == '.') { break; } else { extensionImage = fileName.charAt(i) + extensionImage; } } String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String fieldName = item.getFieldName(); // saves the file on disk item.write(storeFile); arrLinkImage[indexImage++] = item.getName(); } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // request.setAttribute("arrLinkImage", arrLinkImage); // RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add"); // rd.forward(request, response); // String sessionId = request.getAttribute("sessionIdAdmin").toString(); String sessionId = request.getSession().toString(); String groupId = request.getParameter("groupId"); Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId); response.setContentType("text/html"); }
From source file:com.assignment.elance.controller.FileUploadServlet.java
/** * Upon receiving file upload submission, parses the request to read upload * data and saves the file on disk.//from w w w . j a v a2s. c o m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + SystemAttributes.UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String file = randomFileNameGenerator(); String filePath = uploadPath + File.separator + file; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); FilesManager fm = new FilesManager(); boolean send_dir = false; switch (Integer.parseInt(request.getParameter("senddir"))) { case 0: send_dir = false; break; case 1: send_dir = true; break; } fm.insert(fileName, file, Integer.parseInt(request.getParameter("jobId")), send_dir); request.setAttribute("message", "Upload has been done successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // // redirects client to message page // getServletContext().getRequestDispatcher("/message.jsp").forward( // request, response); switch (Integer.parseInt(request.getParameter("callbackpage"))) { case 0: response.sendRedirect("projectOverview.jsp?pId=" + Integer.parseInt(request.getParameter("jobId"))); break; case 1: response.sendRedirect("project.jsp?jobId=" + Integer.parseInt(request.getParameter("jobId"))); break; } }