List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*ww w. ja v a 2s . c o m*/ * */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
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. 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 { 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:mercury.DigitalMediaController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {/*from ww w. j a va2 s. c o m*/ List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { Integer serial = (new DigitalMediaDAO()).uploadToDigitalMedia(item); String filename = item.getName(); if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/') + 1); } String id = serial + ":" + filename; String encodedId = new String(new Base64().encode(id.getBytes())); encodedId = encodedId.replaceAll("\\\\", "_"); if (serial != null && serial != 0) { response.getWriter().write("{success: true, id: \"" + encodedId + "\"}"); return; } } } } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().write("{success: false}"); } else { String decodedId = null; DigitalMediaDTO dto = null; try { String id = request.getParameter("id"); id = id.replaceAll("_", "\\\\"); decodedId = new String(new Base64().decode(id.getBytes())); String[] splitId = decodedId.split(":"); if (splitId.length == 2 && splitId[0].matches("^\\d+$")) { dto = (new DigitalMediaDAO()).getDigitalMedia(Integer.valueOf(splitId[0]), splitId[1]); } } catch (Exception e) { // dto should be null here } InputStream in = null; byte[] bytearray = null; int length = 0; String defaultFile = request.getParameter("default"); response.reset(); try { if (dto != null && dto.getIn() != null) { response.setContentType(dto.getMimeType()); response.setHeader("Content-Disposition", "filename=" + dto.getFileName()); length = dto.getLength(); in = dto.getIn(); } if (in == null && StringUtils.isNotBlank(defaultFile)) { String path = getServletContext().getRealPath("/"); File file = new File(path + defaultFile); length = (int) file.length(); in = new FileInputStream(file); } if (in != null) { bytearray = new byte[length]; int index = 0; OutputStream os = response.getOutputStream(); while ((index = in.read(bytearray)) != -1) { os.write(bytearray, 0, index); } in.close(); } else { response.getWriter().write("{success: false}"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{success: false}"); } response.flushBuffer(); } }
From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("--- BEGIN DOPOST ---"); request.setCharacterEncoding("UTF-8"); request.setAttribute(RETVAL, "0"); request.setAttribute(FILEURL, ""); request.setAttribute(ERRORMESSAGE, ""); String newName = ""; String hash = ""; // ???//from w ww. java2 s. com VWBContext context = VWBContext.createContext(request, VWBCommand.ATTACH, null); rb = context.getBundle("templates/default"); if (!context.getVWBSession().isAuthenticated()) { request.setAttribute(RETVAL, "212"); request.setAttribute(ERRORMESSAGE, rb.getString("uploader.nopermission")); } else { if (enabled) { try { Map<String, Object> fields = parseFileItem(request); FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; long fileSize = uplFile.getSize(); InputStream in = uplFile.getInputStream(); if (fileSize == 0 || in == null) { if (debug) log.error("The upload file size is 0 or inputstream is null!"); request.setAttribute(RETVAL, "211"); request.setAttribute(ERRORMESSAGE, rb.getString("error.doc.zerolength")); } else { HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("title", fileName); hashMap.put("summary", ""); hashMap.put("page", (String) fields.get("pageName")); hashMap.put("signature", (String) fields.get("signature")); hashMap.put("rightType", (String) fields.get("rightType")); hashMap.put("cachable", (String) fields.get("cachable")); hash = executeUpload(request, context, in, fileName, fileSize, hashMap, response); } newName = fileName; } catch (Exception ex) { log.debug("Error on upload picture", ex); request.setAttribute(RETVAL, "203"); request.setAttribute(ERRORMESSAGE, rb.getString("uploader.parsepara")); } } else { request.setAttribute(RETVAL, "1"); request.setAttribute(ERRORMESSAGE, rb.getString("uploader.invalidxml")); } } printScript(request, response, newName, hash); log.debug("--- END DOPOST ---"); }
From source file:UploadDownloadFile.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response);/*w ww . ja v a 2 s.c o m*/ String filePath; final String clientip = request.getRemoteAddr().replace(":", "_"); filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/" + clientip + "/"; System.out.println("filePath = " + filePath); // filePath = "/Users/jhovarie/Desktop/webuploaded/"; File f = new File(filePath); if (!f.exists()) { f.mkdirs(); } 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")); factory.setRepository(new File(filePath)); // 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("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>"); String fileName = ""; 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(); // 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("Target Location = " + filePath); out.write( "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>"); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println("Error in Process " + ex); } }
From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w . ja v a 2s .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"); String action = request.getParameter("action"); System.out.println("action: " + action); if (action == null || action.isEmpty()) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //PriceDAO priceDAO = new PriceDAO(); try { List<FileItem> fields = upload.parseRequest(request); //out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); while (it.hasNext()) { FileItem fileItem = it.next(); //store in webserver. String fileName = fileItem.getName(); if (fileName != null) { File file = new File(fileName); fileItem.write(file); System.out.println("File successfully saved as " + file.getAbsolutePath()); //process file Reader in = new FileReader(file.getAbsolutePath()); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in); for (CSVRecord record : records) { String name = record.get("<name>"); String login = record.get("<login>"); String title = record.get("<title>"); String email = record.get("<email>"); String role = record.get("<role>"); String dept = record.get("<department>"); String joinDate = record.get("<joinDate>"); String probDate = record.get("<probDate>"); String annLeaveEnt = record.get("<leave_entitlement>"); String annBal = record.get("<leave_bal>"); String annMax = record.get("<leave_max>"); String annCF = record.get("<leave_cf>"); String med = record.get("<med_taken>"); String oil = record.get("<oil_taken>"); String unpaid = record.get("<unpaid_taken>"); String child = record.get("<child_bal>"); TitleDTO titleDto = titleBean.getTitleByName(title); RoleDTO roleDto = accessBean.getRole(role); DeptDTO deptDto = deptBean.getDepartment(dept); //create the user first UserDTO user = new UserDTO(); user.setName(name); user.setLogin(login); user.setTitle(titleDto); user.setEmail(email); user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy")); user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy")); //store in user table. userBean.createUser(user); //assign role userBean.assignRole(user, roleDto); //assign dept deptBean.assignEmployee(user, deptDto); //leave ent LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual"); LeaveEntDTO annualentDTO = new LeaveEntDTO(); annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt)); annualentDTO.setBalance(Double.parseDouble(annBal)); annualentDTO.setMax(Double.parseDouble(annMax)); annualentDTO.setCarriedOver(Double.parseDouble(annCF)); annualentDTO.setLeaveType(lvtypeDTO); //assign annual leave annualentDTO.setUser(user); leaveBean.addLeaveEnt(annualentDTO); //medical ent LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave"); LeaveEntDTO medentDTO = new LeaveEntDTO(); medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med)); medentDTO.setCurrent(medTypeDTO.getDays()); medentDTO.setUser(user); medentDTO.setLeaveType(medTypeDTO); leaveBean.addLeaveEnt(medentDTO); //oil ent LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu"); LeaveEntDTO oilentDTO = new LeaveEntDTO(); oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil)); oilentDTO.setCurrent(0); oilentDTO.setUser(user); oilentDTO.setLeaveType(oilTypeDTO); leaveBean.addLeaveEnt(oilentDTO); //unpaid LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid"); LeaveEntDTO unpaidentDTO = new LeaveEntDTO(); unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid)); unpaidentDTO.setCurrent(0); unpaidentDTO.setUser(user); unpaidentDTO.setLeaveType(unpaidTypeDTO); leaveBean.addLeaveEnt(unpaidentDTO); //child LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care"); double cur = childTypeDTO.getDays(); LeaveEntDTO childentDTO = new LeaveEntDTO(); childentDTO.setBalance(cur - Double.parseDouble(child)); childentDTO.setCurrent(cur); childentDTO.setUser(user); childentDTO.setLeaveType(childTypeDTO); leaveBean.addLeaveEnt(childentDTO); } /* if (stockPrices.size() > 0) { priceDAO.OpenConnection(); priceDAO.updateStockPrice(stockPrices); } */ } } } catch (Exception e) { e.printStackTrace(); } finally { //priceDAO.CloseConnection(); RequestDispatcher dispatcher = request.getRequestDispatcher("/employee"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } } else { RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } }
From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java
/** * Do the effective upload of files.// w w w . j a v a 2 s . c o m * * @param session the HttpSession * @param request the multpart request * @throws IOException */ @SuppressWarnings("unchecked") private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException { try { session.setAttribute(UPLOAD_ERRORS, ""); session.setAttribute(UPLOAD_FATAL_ERROR, ""); List<String> paths = new ArrayList<String>(); session.setAttribute(FILE_UPLOAD_PATHS, paths); FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); startingToSaveUploadedFile(session); String errorMessage = ""; for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { try { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { errorMessage += "The file " + filename + " is not uploaded!"; errorMessage += (StringUtil.isDefined(whiteList) ? " Only " + whiteList.replaceAll(" ", ", ") + " file types can be uploaded<br/>" : " No allowed file format has been defined for upload<br/>"); session.setAttribute(UPLOAD_ERRORS, errorMessage); } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } } } finally { fileItem.delete(); } } } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); session.setAttribute(UPLOAD_FATAL_ERROR, "Could not process uploaded file. Please see log for details."); } finally { endingToSaveUploadedFile(session); } }
From source file:com.fredck.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * //from w w w . ja v a 2 s. com * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("ConnectorServlet.doPost"); if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } System.out.println("1111111111111111111111"); out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:Index.RegisterClienteImagesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . j a 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"); try (PrintWriter out = response.getWriter()) { String ubicacionArchivo = "~\\NetBeansProjects\\QuickOrderWeb\\web\\images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(ubicacionArchivo)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); webservice.Cliente client = new webservice.Cliente(); for (FileItem item : partes) { client = (webservice.Cliente) request.getSession().getAttribute("registroUsuario"); File file = new File(ubicacionArchivo, client.getNickname() + ".jpg"); item.write(file); System.out.println("name: " + item.getName()); client.setImagen(client.getNickname() + ".jpg"); } QuickOrderWebService webService = new QuickOrderWebService(); ControllerInterface port = webService.getQuickOrderWebServicePort(); port.registrarCliente(client); request.setAttribute("error", null); request.setAttribute("agregado", "OK"); request.removeAttribute("registroUsuario"); request.getSession().removeAttribute("userName"); request.getRequestDispatcher("/AltaCliente.jsp").forward(request, response); } catch (FileUploadException ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.setAttribute("error", "Error al subir la imagen"); request.setAttribute("funcionalidad", "Imagen"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } catch (Exception ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.setAttribute("error", "Error al subir la imagen"); request.setAttribute("funcionalidad", "Imagen"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } } }
From source file:controller.productServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String proimage = ""; String nameProduct = ""; double priceProduct = 0; String desProduct = ""; String colorProduct = ""; int years = 0; int catId = 0; int proid = 0; String command = ""; 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();//w w w .ja va 2 s. co m 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 + 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()) { proimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + proimage; File storeFile = new File(filePath); System.out.println(proimage); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameProduct = item.getString(); } else if (item.getFieldName().equals("price")) { priceProduct = Double.parseDouble(item.getString()); } else if (item.getFieldName().equals("description")) { desProduct = item.getString(); System.out.println(desProduct); } else if (item.getFieldName().equals("color")) { colorProduct = item.getString(); } else if (item.getFieldName().equals("years")) { years = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogory_name")) { catId = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("proid")) { proid = Integer.parseInt(item.getString()); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameProduct.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } try { if (error.length() == 0) { ProductEntity p = new ProductEntity(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years); switch (command) { case "insert": prod.insertProduct(p); url = "/java/admin/ql-product.jsp"; break; case "update": prod.updateProduct(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years, proid); url = "/java/admin/ql-product.jsp"; break; } } else { url = "/java/admin/add-product.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }