List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java
protected void workingdoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/plain"); out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>"); out.println();/*from w ww. j a v a 2 s . c o m*/ DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /* * Set the size threshold, above which content will be stored on disk. */ fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB /* * Set the temporary directory to store the uploaded files of size above * threshold. */ fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { /* * Parse the request */ List<FileItem> items = uploadHandler.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString()); } else { // Handle Uploaded files. out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); /* * Write file to the ultimate location. */ File file = new File(destinationDir, "LogisticNetwork.mxe"); item.write(file); } out.close(); } } catch (FileUploadException ex) { log("Error encountered while parsing the request", ex); } catch (Exception ex) { log("Error encountered while uploading file", ex); } }
From source file:com.insurance.manage.UploadFile.java
private void uploadLicense(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;/*from w ww . ja v a 2 s . com*/ String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // System.out.println("eCust : "+session.getAttribute("eCust")); // if (session.getAttribute("eCust")!=null) { // Customer cEntity = (Customer)request.getAttribute("eCust"); // System.out.println("CustId : "+cEntity.getName()); // } // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; Calendar calendar = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); // System.out.println("custId : "+custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); // System.out.println("year : "+year); } if (item.getFieldName().equals("license") && !item.getString().equals("")) { license = (String) session.getAttribute(item.getString()); // System.out.println("license : "+license+" : "+session.getAttribute(item.getString())); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); if (item.getFieldName().equals("vat") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/vat/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "vatpic", year + fileName); } if (item.getFieldName().equals("car") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/car/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "carpic", year + fileName); } if (item.getFieldName().equals("act") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/act/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "actpic", year + fileName); } if (item.getFieldName().equals("chk") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/chk/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "chkpic", year + fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:application.controllers.admin.EditEmotion.java
private String uploadNewImage(HttpServletRequest request, HttpServletResponse response) { String linkImage = emotionSelected.linkImage; if (!ServletFileUpload.isMultipartContent(request)) { return ""; }/* w w w . ja v a2s . c o m*/ // 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 //groupEmotionId chinh la folder chua // creates the directory if it does not exist String[] arrLink = emotionSelected.linkImage.split("/"); if (arrLink.length < 3) { return ""; } try { List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.isFormField()) { //form field if (item.getFieldName().equals("groupEmotion")) { try { if (emotionSelected.groupEmotionId != Integer.parseInt(item.getString())) { //thay doi group id --> chuyen file sang folder tuong ung va thay doi imagelink //chuyen file sang folder tuong ung theo group da chon String sourcePath = Registry.get("imageHost") + emotionSelected.linkImage; //item.getString --> groupEmotion chon String desPath = Registry.get("imageHost") + "/emotions-image/" + item.getString() + "/" + arrLink[3]; File sourceDir = new File(sourcePath); File desDir = new File(desPath); if (sourceDir.exists()) { FileUtils.copyFile(sourceDir, desDir); sourceDir.delete(); } emotionSelected.groupEmotionId = Integer.parseInt(item.getString()); linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3]; } } catch (NumberFormatException ex) { ex.printStackTrace(); } } if (item.getFieldName().equals("description")) { emotionSelected.description = item.getString(); } if (item.getFieldName().equals("imageURL")) { emotionSelected.linkImage = item.getString(); } } else { String fileName = new File(item.getName()).getName(); //file name bang empty khi ko upload new image if ("".equals(fileName)) { continue; } String filePath = Registry.get("imageHost") + emotionSelected.linkImage; File newImage = new File(filePath); File oldImage = new File(filePath); // xoa image cu bi edit if (oldImage.exists()) { oldImage.delete(); } // save image moi vao folder cua group id va cung ten moi image cu item.write(newImage); //save lai file cua image moi linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3]; } } } catch (Exception ex) { Logger.getLogger(EditEmotion.class.getName()).log(Level.SEVERE, null, ex); } return linkImage; }
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/*w w w .ja v a 2s. c o 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:cn.trymore.core.web.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); try {/*from w ww . ja v a 2s. c om*/ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); diskFileItemFactory.setRepository(new File(this.tempPath)); String fileIds = ""; ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request); Iterator<FileItem> itor = fileList.iterator(); Iterator<FileItem> itor1 = fileList.iterator(); String file_type = ""; while (itor1.hasNext()) { FileItem item = itor1.next(); if (item.isFormField() && "file_type".equals(item.getFieldName())) { file_type = item.getString(); } } FileItem fileItem; while (itor.hasNext()) { fileItem = itor.next(); if (fileItem.getContentType() == null) { continue; } // obtains the file path and name String filePath = fileItem.getName(); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); // generates new file name with the current time stamp. String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName); // ensure the directory existed before creating the file. File dir = new File( this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1)); if (!dir.exists()) { dir.mkdirs(); } // stream writes to the destination file fileItem.write(new File(this.uploadPath + "/" + newFileName)); ModelFileAttach fileAttach = null; if (request.getParameter("noattach") == null) { // storages the file into database. fileAttach = new ModelFileAttach(); fileAttach.setFileName(fileName); fileAttach.setFilePath(newFileName); fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize())); fileAttach.setNote(this.getStrFileSize(fileItem.getSize())); fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1)); fileAttach.setCreatetime(new Date()); fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL); fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat); ModelAppUser user = ContextUtil.getCurrentUser(); if (user != null) { fileAttach.setCreatorId(Long.valueOf(user.getId())); fileAttach.setCreator(user.getFullName()); } else { fileAttach.setCreator("Unknow"); } this.serviceFileAttach.save(fileAttach); } //add by Tang ??fileIds????? if (fileAttach != null) { fileIds = (String) request.getSession().getAttribute("fileIds"); if (fileIds == null) { fileIds = fileAttach.getId(); } else { fileIds = fileIds + "," + fileAttach.getId(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.println( "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"") + ", \"url\":\"" + newFileName + "\"}}"); } request.getSession().setAttribute("fileIds", fileIds); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\""); } }
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww .j a va 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:com.mingsoft.basic.servlet.UploadServlet.java
/** * ?post/*from w w w .java2 s .c o m*/ * @param req HttpServletRequest * @param res HttpServletResponse * @throws ServletException ? * @throws IOException ? */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=utf-8"); PrintWriter out = res.getWriter(); String uploadPath = this.getServletContext().getRealPath(File.separator); // String isRename = "";// ???? true:??? String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";// FileUtil.createFolder(_tempPath); File tempPath = new File(_tempPath); // int maxSize = 1000000; // ??,?? 1000000/1024=0.9M //String allowedFile = ".jpg,.gif,.png,.zip"; // ? String deniedFile = ".exe,.com,.cgi,.asp"; // ?? DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory // ????? factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() // ?SizeThreshold? factory.setRepository(tempPath); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown try { List fileItems = upload.parseRequest(req); Iterator iter = fileItems.iterator(); // ???? String regExp = ".+\\\\(.+)$"; // String[] errorType = deniedFile.split(","); Pattern p = Pattern.compile(regExp); String outPath = ""; //?? while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("uploadPath")) { outPath += item.getString(); uploadPath += outPath; } else if (item.getFieldName().equals("isRename")) { isRename = item.getString(); } else if (item.getFieldName().equals("maxSize")) { maxSize = Integer.parseInt(item.getString()) * 1048576; } else if (item.getFieldName().equals("allowedFile")) { // allowedFile = item.getString(); } else if (item.getFieldName().equals("deniedFile")) { deniedFile = item.getString(); } else if (!item.isFormField()) { // ??? String name = item.getName(); long size = item.getSize(); if ((name == null || name.equals("")) && size == 0) continue; try { // ?? 1000000/1024=0.9M upload.setSizeMax(maxSize); // ? // ? String fileName = System.currentTimeMillis() + name.substring(name.indexOf(".")); String savePath = uploadPath + File.separator; FileUtil.createFolder(savePath); // ??? if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) { savePath += fileName; outPath += fileName; } else { savePath += name; outPath += name; } item.write(new File(savePath)); out.print(outPath.trim()); logger.debug("upload file ok return path " + outPath); out.flush(); out.close(); } catch (Exception e) { this.logger.debug(e); } } } } catch (FileUploadException e) { this.logger.debug(e); } }
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. j a va 2s. c o 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); }
From source file:graphvis.webui.servlets.UploadServlet.java
/** * This method receives POST from the index.jsp page and uploads file, * converts into the correct format then places in the HDFS. *//*from w ww . j a v a 2s .c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { response.setStatus(403); return; } File tempDirFileObject = new File(Configuration.tempDirectory); // Create/remove temp folder if (tempDirFileObject.exists()) { FileUtils.deleteDirectory(tempDirFileObject); } // (Re-)create temp directory tempDirFileObject.mkdir(); FileUtils.copyFile( new File(getServletContext() .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")), new File(Configuration.tempDirectory + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")); FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")), new File(Configuration.tempDirectory + "/dist-graphvis.jar")); // 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(Configuration.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"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(Configuration.MAX_REQUEST_SIZE); String fileName = ""; try { // Parse the request List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = Configuration.tempDirectory + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory try { item.write(uploadedFile); } catch (Exception ex) { throw new ServletException(ex); } } } String fullFilePath = Configuration.tempDirectory + File.separator + fileName; String extension = FilenameUtils.getExtension(fullFilePath); // Load Files intoHDFS // (This is where we do the parsing.) loadIntoHDFS(fullFilePath, extension); getServletContext().setAttribute("fileName", new File(fullFilePath).getName()); getServletContext().setAttribute("fileExtension", extension); // Displays fileUploaded.jsp page after upload finished getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } }
From source file:admin.controller.ServletUpdateFonts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.j av a2s .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 */ @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) { } } }