List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:Control.HandleAddFoodMenu.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j av 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 ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); Food temp = new Food(); try (PrintWriter out = response.getWriter()) { LinkedList<String> names = new LinkedList<>(); /* TODO output your page here. You may use following sample code. */ String path = getClass().getResource("/").getPath(); String[] tempS = null; if (Paths.path == null) { File file = new File(path + "test.html"); path = file.getParent(); File file1 = new File(path + "test1.html"); path = file1.getParent(); File file2 = new File(path + "test1.html"); path = file2.getParent(); Paths.path = path; } else { path = Paths.path; } path = Paths.tempPath; String name; String sepName = Tools.CurrentTime(); if (ServletFileUpload.isMultipartContent(request)) { List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Iterator iter = multiparts.iterator(); int index = 0; tempS = new String[multiparts.size() - 1]; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { name = new File(item.getName()).getName(); names.add(name); String FilePath = path + Paths.foodImagePath + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.categoryid = Integer.parseInt(tempS[index++]); temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.price = Double.parseDouble(tempS[index++]); temp.pieces = Integer.parseInt(tempS[index++]); temp.description = tempS[index++]; temp.restid = Integer.parseInt(tempS[index++]); temp.resID = tempS[index++]; temp.rename = tempS[index++]; } if (Food.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddMenu.jsp?index=1" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { if (Food.addNewFood(temp)) { int id = Food.getFoodID(temp.ID); boolean flag = true; for (String s : names) { if (Image.addImage(s, Paths.foodImagePathStore + sepName + s, id)) { } else { flag = false; break; } } if (flag) { response.sendRedirect("./Admin/AddMenu.jsp?index=2" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { response.sendRedirect("./Admin/AddMenu.jsp?index=4" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } else { response.sendRedirect("./Admin/AddMenu.jsp?index=3" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } } catch (Exception e) { response.sendRedirect("./Admin/AddMenu.jsp?index=0" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } }
From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doPost"); String fileName = null;/*from w w w . j ava2s .com*/ String contentType; byte[] document = null; FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(request); if (!items.isEmpty()) { fileName = items.get(0).getName(); // contentType = items.get(0).getContentType(); document = items.get(0).get(); } } catch (FileUploadException e) { throw new ServletException(e); } String extension = FilenameUtils.getExtension(fileName).toLowerCase(); contentType = supportedFileExtensions.get(extension); if (null == contentType) { /* * Unsupported content-type is converted to a ZIP container. */ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); ZipEntry zipEntry = new ZipEntry(fileName); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(document, zipOutputStream); zipOutputStream.close(); fileName = FilenameUtils.getBaseName(fileName) + ".zip"; document = outputStream.toByteArray(); contentType = "application/zip"; } LOG.debug("File name: " + fileName); LOG.debug("Content Type: " + contentType); String signatureRequest = new String(Base64.encode(document)); request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document); request.getSession().setAttribute("SignatureRequest", signatureRequest); request.getSession().setAttribute("ContentType", contentType); response.sendRedirect(request.getContextPath() + this.postPage); }
From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { try {/* w w w . j a v a 2 s. c om*/ String userName = loggedInUser.getUserName(); String sessionid = (String) session.getId(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += userName + "_" + sessionid; //variables String fileName = "", ext = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (!fileItem.isFormField()) { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext) && !"PNG".equalsIgnoreCase(ext)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid image. Please upload JPG or PNG file"); return (new MyProfileAction().execute(request, response)); } file = new File(tempFilePath + "." + ext); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return (new MyProfileAction().execute(request, response)); } } } //if if (file.length() <= 0) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new MyProfileAction().execute(request, response)); } if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file"); return (new MyProfileAction().execute(request, response)); } User user = loggedInUser; user.setProfilePicture(file); UserDAO.getInstance().setProfilePicture(user); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Profile picture update")); } catch (Exception e) { e.printStackTrace(System.out); } } request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully"); return (new MyProfileAction().execute(request, response)); }
From source file:communicator.doMove.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.jav 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"); PrintWriter out = null; JSONObject outputObject = new JSONObject(); try { HashMap<String, String> bigItemIds = new HashMap<>(); Iterator mIterator = bigItemIds.keySet().iterator(); out = response.getWriter(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); final String moveId = UUID.randomUUID().toString(); final MovesDb movesDb = new MovesDb(); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { System.out.println("Form field" + item.getString()); bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb); mIterator = bigItemIds.keySet().iterator(); System.out.println("ITEM ID SIZE " + bigItemIds.size()); } else { //processUploadedFile(item); System.out.print("Photo Field"); String key = (String) mIterator.next(); File mFile = new File(bigItemIds.get(key)); item.write(mFile); } } new Thread() { public void run() { pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue(); moveToMailQueue.pushMoveToMailQueue(movesDb); } }.start(); outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS); outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); } catch (Exception ex) { outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE); outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:edu.lafayette.metadb.web.dataman.ImportAdminDesc.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *///w ww . j ava 2 s. c o m @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String delimiter = "comma"; boolean replaceEntity = false; String projname = (String) request.getSession(false).getAttribute(Global.SESSION_PROJECT); JSONObject output = new JSONObject(); try { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ Iterator it = fileItemsList.iterator(); InputStream input = null; while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { /* The file item contains a simple name-value pair of a form field */ if (fileItem.getFieldName().equals("delimiter")) delimiter = fileItem.getString(); else if (fileItem.getFieldName().equals("replace-entity")) replaceEntity = true; } else { input = fileItem.getInputStream(); } } String delimiterType = "csv"; if (delimiter.equals("tab")) { delimiterType = "tsv"; } if (input != null) { Result res = DataImporter.importFile(delimiterType, projname, input, replaceEntity); if (res.isSuccess()) { HttpSession session = request.getSession(false); if (session != null) { String userName = (String) session.getAttribute(Global.SESSION_USERNAME); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "Data imported into project " + projname); } output.put("message", "Data import successfully"); } else { output.put("message", "The following fields have been changed:"); StringBuilder fields = new StringBuilder(); for (String field : (ArrayList<String>) res.getData()) fields.append(field + ','); output.put("fields", fields.toString()); } output.put("success", res.isSuccess()); } else { output.put("success", false); output.put("message", "Null data"); } } else { output.put("success", false); output.put("message", "Form is not multi-part"); } } catch (Exception e) { MetaDbHelper.logEvent(e); } out.print(output); out.flush(); }
From source file:CourseFileManagementSystem.Upload.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("<html><head></head><body>"); // Check that we have a file upload request 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();//from w w w. j a v a 2 s .co m 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 temp_folder = " "; try { String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; temp_folder = dataFolder; File uploadD = new File(dataFolder); if (!uploadD.exists()) { uploadD.mkdir(); } ResultList rs5 = DB.query( "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode " + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID=" + sectionID); rs5.next(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); // creates the directory if it does not exist String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/"; String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester"); String real_path = temp_folder + File.separator + temp_semester; File semester = new File(real_path); if (!semester.exists()) { semester.mkdir(); } path1 += temp_semester + "/"; real_path += File.separator; String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-" + rs5.getString("courseName"); String real_path1 = real_path + temp_course; File course = new File(real_path1); if (!course.exists()) { course.mkdir(); } path1 += temp_course + "/"; real_path1 += File.separator; String temp_section = "section-" + rs5.getString("sectionNo"); String real_path2 = real_path1 + temp_section; File section = new File(real_path2); if (!section.exists()) { section.mkdir(); } path1 += temp_section + "/"; real_path2 += File.separator; String sectionPath = path1; // Parse the request List<FileItem> items = upload.parseRequest(request); if (items != null && items.size() > 0) { // iterates over form's fields for (FileItem item : items) { // processes only fields that are not form fields if (!item.isFormField() && !item.getName().equals("")) { String DBPath = ""; System.out.println(item.getName() + " file is for " + item.getFieldName()); Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+"); int id = field_name.nextInt(); fileName = new File(item.getName()).getName(); ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id); rs.next(); String temp_file = rs.getString("label"); String real_path3 = real_path2 + temp_file; File file_type = new File(real_path3); if (!file_type.exists()) file_type.mkdir(); DBPath = sectionPath + "/" + temp_file + "/"; String context_path = DBPath; real_path3 += File.separator; String filePath = real_path3 + fileName; DBPath += fileName; String temp_DBPath = DBPath; int count = 0; File f = new File(filePath); String temp_fileName = f.getName(); String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName); String extension = FilenameUtils.getExtension(filePath); String newFullPath = filePath; String tempFileName = " "; while (f.exists()) { ++count; tempFileName = fileNameWithOutExt + "_(" + count + ")."; newFullPath = real_path3 + tempFileName + extension; temp_DBPath = context_path + tempFileName + extension; f = new File(newFullPath); } filePath = newFullPath; System.out.println("New path: " + filePath); DBPath = temp_DBPath; String changeFilePath = filePath.replace('/', '\\'); String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", ""); File uploadedFile = new File(changeFilePath1); System.out.println("Change filepath = " + changeFilePath1); System.out.println("DBPath = " + DBPath); // saves the file to upload directory item.write(uploadedFile); String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')"; DB.update(query); ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id); while (rs3.next()) { String label = rs3.getString("label"); out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label + "</a>"); out.write("<br><br>"); } ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1"); rs4.next(); String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values(" + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")"; DB.update(query2); } } } } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } response.sendRedirect(request.getHeader("Referer")); }
From source file:cust_photo_upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a va 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"); HttpSession hs = request.getSession(); try (PrintWriter out = response.getWriter()) { Login ln = (Login) hs.getAttribute("user"); String pname = ln.getUName(); String p = ""; // // creates FileItem instances which keep their content in a temporary file on disk FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //get the list of all fields from request List<FileItem> fields = upload.parseRequest(request); // iterates the object of list Iterator<FileItem> it = fields.iterator(); //getting objects one by one while (it.hasNext()) { //assigning coming object if list to object of FileItem FileItem fileItem = it.next(); //check whether field is form field or not boolean isFormField = fileItem.isFormField(); if (isFormField) { //get the filed name String fieldName = fileItem.getFieldName(); } else { String extension; String fieldName = fileItem.getFieldName(); if (fieldName.equals("photo")) ; { //getting name of file p = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring extension = p.substring(p.indexOf(".") + 1, p.length()); ; //rename file...concate name and extension p = pname + "." + extension; try { String filePath = this.getServletContext().getRealPath("/images") + "\\"; fileItem.write(new File(filePath + p)); } catch (Exception ex) { out.println(ex.toString()); } } } } // hs.setAttribute("photo", photo); // SessionFactory sf=NewHibernateUtil.getSessionFactory(); // Session s=sf.openSession(); // Transaction t=s.beginTransaction(); // Imagedata im=new Imagedata(); // im.setIname(pname); // im.setIurl(photo); // s.save(im); // t.commit(); // RequestDispatcher rd = request.getRequestDispatcher("viewserv"); rd.forward(request, response); // response.sendRedirect("viewserv"); } catch (Exception ex) { out.println(ex.getMessage()); } }
From source file:de.knurt.fam.core.model.config.FileUploadController.java
public FileUploadController(TemplateResource tr, HttpServletResponse response) { reinitOptions();//ww w. j av a2s . c om this.tr = tr; this.response = response; this.factory = new DiskFileItemFactory(); this.mftm = new MimetypesFileTypeMap(); this.uploadDir = new FileOfUser(tr.getAuthUser()).getUploadDir(); }
From source file:controller.AddNewEC.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w.ja 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 { response.setContentType("text/html;charset=UTF-8"); ExtenuatingCircumstance ec = new ExtenuatingCircumstance(); if (ServletFileUpload.isMultipartContent(request)) { try { int year = 0; String fname = StringUtils.EMPTY; String title = StringUtils.EMPTY; String desciption = StringUtils.EMPTY; List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); ArrayList<FileItem> files = new ArrayList<>(); for (FileItem item : multiparts) { if (item.isFormField()) { if (item.getFieldName().equals("year")) { year = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("title")) { title = item.getString(); } if (item.getFieldName().equals("description")) { desciption = item.getString(); } } else { if (StringUtils.isNotEmpty(item.getName())) { files.add(item); } } } HttpSession session = request.getSession(false); Account studentAccount = (Account) session.getAttribute("account"); LocalDateTime now = WsadUtils.GetCurrentDatetime(); // insert EC ec.setAcademicYear(year); ec.setTitle(title); ec.setDescription(desciption); ec.setProcess_status("submitted"); ec.setSubmitted_date(now.toString()); ec.setAccount(studentAccount.getId()); ExtenuatingCircumstance insertedEC = new ExtenuatingCircumstanceDAO().insertEC(ec); //insert assigned coordinator Account coordinator = new AccountDAO().getCoordinator(studentAccount.getFaculty()); insertAssignedCoordinator(coordinator, insertedEC); //insert evidence insertedEvidence(files, now, insertedEC, studentAccount); String mailContent = WsadUtils.buildMailContentForNewEC(insertedEC); SendMail.sendMail(coordinator.getEmail(), "New EC", mailContent); } catch (Exception e) { e.printStackTrace(); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } request.setAttribute("resultMsg", "inserted"); request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response); }
From source file:admin.controller.ServletAddPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . jav 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 */ 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 { String uploadPath = 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("/tmp")); // 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 field_name = fi.getFieldName(); if (field_name.equals("brandname")) { brand_name = fi.getString(); } if (field_name.equals("look")) { look_id = fi.getString(); } } else { check = brand.checkAvailability(brand_name); if (check == false) { field_name = fi.getFieldName(); file_name = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = brand_name + "_" + Str + ".jpeg"; file_name = brand_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); brand.addBrands(brand_name, Integer.parseInt(look_id), file_name); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); out.println("Uploaded Filename: " + filePath + "<br>"); } else { response.sendRedirect( request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist"); } } } 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 { try { out.close(); } catch (Exception e) { logger.log(Level.SEVERE, "", e); } } }