List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:Controller.ControllerImage.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//w w w . ja v a 2s. co m * @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); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; String code = (String) params.get("txtCode"); String name = (String) params.get("txtName"); String price = (String) params.get("txtPrice"); int a = Integer.parseInt(price); String image = (String) params.get("txtImage"); //Update product if (fileName.equals("")) { Products sp = new Products(); sp.Update(code, name, price, image); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } else { // bat dau ghi file File savedFile = new File(RealPath); item.write(savedFile); //ket thuc ghi Products sp = new Products(); sp.Update(code, name, price, "upload\\" + fileName); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } } catch (Exception e) { RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp"); rd.forward(request, response); } } } } this.processRequest(request, response); }
From source file:azkaban.web.JobManagerServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) throw new ServletException("No job file found!"); Map<String, Object> params = this._multipartParser.parseMultipart(request); try {//w w w .j a va2s . c o m final AzkabanApplication app = getApplication(); final JobManager jobManager = app.getJobManager(); FileItem item = (FileItem) params.get("file"); String deployPath = (String) params.get("path"); File jobDir = extractFile(item); jobManager.deployJobDir(jobDir.getAbsolutePath(), deployPath); } catch (Exception e) { log.info("Installation Failed.", e); String redirectError = (String) params.get("redirect_error"); setMessagedUrl(response, redirectError, "Installation Failed: " + e.getLocalizedMessage()); return; } String redirectSuccess = (String) params.get("redirect_success"); setMessagedUrl(response, redirectSuccess, "Installation Succeeded"); }
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 w w w.java 2 s . com * @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:Control.HandleAddRestaurant.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww 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, FileUploadException, Exception { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* 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; Restaurant temp = new Restaurant(); String name = null; 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(); String FilePath = path + Paths.logoPathStore + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.address = tempS[index++]; temp.city = tempS[index++]; temp.state = tempS[index++]; temp.zipcode = tempS[index++]; temp.email = tempS[index++]; temp.phone = tempS[index++]; temp.monHours = tempS[index++]; temp.sunHours = tempS[index++]; temp.minPrice = Double.parseDouble(tempS[index++]); temp.fee = Double.parseDouble(tempS[index++]); temp.type = Integer.parseInt(tempS[index++]); temp.logoImage = Paths.logoPath + sepName + name; } if (Restaurant.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=1"); } else { if (Restaurant.addNewRestaurant(temp)) { Tools.updateRestaurants(session); response.sendRedirect("./Admin/AddRestaurant.jsp?index=2"); } else { response.sendRedirect("./Admin/AddRestaurant.jsp?index=3"); } } } catch (Exception e) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=0"); } }
From source file:Controller.ControllerImageCustomerIndex.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w. j a va 2s .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); String username = (String) params.get("txtusername"); String password = (String) params.get("txpassword"); String hoten = (String) params.get("txthoten"); String gioitinh = (String) params.get("txtgioitinh"); String email = (String) params.get("txtemail"); String role = "false"; Customer cus = new Customer(username, password, hoten, gioitinh, email, role, "upload\\" + fileName); CustomerDAO.ThemKhachHang(cus); RequestDispatcher rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:com.priocept.jcr.server.UploadServlet.java
private void process(HttpServletRequest request, HttpServletResponse response) { try {/* w w w .j a va 2s .com*/ if (ServletFileUpload.isMultipartContent(request)) { processFiles(request, response); } else { processQuery(request, response); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Controller.ControllerImageCustomer.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w. ja v a 2 s. c o m*/ * @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); String username = (String) params.get("txtusername"); String password = (String) params.get("txpassword"); String hoten = (String) params.get("txthoten"); String gioitinh = (String) params.get("txtgioitinh"); String email = (String) params.get("txtemail"); String role = "false"; String Register = (String) params.get("Register"); String url = "CustomerDao.jsp"; if (Register.equals("Register")) { url = "index.jsp"; } Customer cus = new Customer(username, password, hoten, gioitinh, email, role, "upload\\" + fileName); CustomerDAO.ThemKhachHang(cus); RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:gsn.http.FieldUpload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String msg;/*from w w w . j a v a2 s. c o m*/ Integer code; PrintWriter out = res.getWriter(); ArrayList<String> paramNames = new ArrayList<String>(); ArrayList<String> paramValues = new ArrayList<String>(); //Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { out.write("not multipart!"); code = 666; msg = "Error post data is not multipart!"; logger.error(msg); } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(5 * 1024 * 1024); List items; try { // Parse the request items = upload.parseRequest(req); //building xml data out of the input String cmd = ""; String vsname = ""; Base64 b64 = new Base64(); StringBuilder sb = new StringBuilder("<input>\n"); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("vsname")) { //define which cmd block is sent sb.append("<vsname>" + item.getString() + "</vsname>\n"); vsname = item.getString(); } else if (item.getFieldName().equals("cmd")) { //define which cmd block is sent cmd = item.getString(); sb.append("<command>" + item.getString() + "</command>\n"); sb.append("<fields>\n"); } else if (item.getFieldName().split(";")[0].equals(cmd)) { //only for the defined cmd sb.append("<field>\n"); sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n"); paramNames.add(item.getFieldName().split(";")[1]); if (item.isFormField()) { sb.append("<value>" + item.getString() + "</value>\n"); paramValues.add(item.getString()); } else { sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n"); paramValues.add(new String(b64.encode(item.get()))); } sb.append("</field>\n"); } } sb.append("</fields>\n"); sb.append("</input>\n"); //do something with xml aka statement.toString() AbstractVirtualSensor vs = null; try { vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS(); vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}), paramValues.toArray(new Serializable[] {})); } catch (VirtualSensorInitializationFailedException e) { logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e); } finally { Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs); } code = 200; msg = "The upload to the virtual sensor went successfully! (" + vsname + ")"; } catch (ServletFileUpload.SizeLimitExceededException e) { code = 600; msg = "Upload size exceeds maximum limit!"; logger.error(msg, e); } catch (Exception e) { code = 500; msg = "Internal Error: " + e; logger.error(msg, e); } } //callback to the javascript out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>"); }
From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java
/** * Processes requests for both HTTP/* w w w . j a v a2 s .c o m*/ * <code>GET</code> and * <code>POST</code> methods. * * @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"); boolean isMultiPart = ServletFileUpload.isMultipartContent(request); log("isMultipartContent: " + isMultiPart); log("Content-Type: " + request.getContentType()); if (isMultiPart) { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); /* * Set the file size limit in bytes. This should be set as an * initialization parameter */ diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB. // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); // Parse the request List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { log("Could not parse request", ex); } PrintWriter out = response.getWriter(); out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>"); ListIterator li = items.listIterator(); while (li.hasNext()) { FileItem fileItem = (FileItem) li.next(); if (fileItem.isFormField()) { processFormField(fileItem); } else { out.append(processUploadedFile(fileItem)); } } out.print("</body></html>"); out.flush(); out.close(); } }
From source file:net.formio.servlet.ServletRequestParams.java
/** * Creates request params extractor.//from w w w .j ava2 s . c o m * @param request request * @param defaultEncoding header and request parameter encoding * @param tempDir temporary directory to store files bigger than specified size threshold * @param sizeThreshold max size of file (in bytes) that is loaded into the memory and not temporarily stored to disk * @param totalSizeMax maximum allowed size of the whole request in bytes * @param singleFileSizeMax maximum allowed size of a single uploaded file */ public ServletRequestParams(HttpServletRequest request, String defaultEncoding, File tempDir, int sizeThreshold, long totalSizeMax, long singleFileSizeMax) { if (request == null) throw new IllegalArgumentException("request cannot be null"); HttpServletRequest r = null; if (ServletFileUpload.isMultipartContent(request)) { ServletFileUploadWrapper wr = new ServletFileUploadWrapper(request, defaultEncoding, tempDir, sizeThreshold, totalSizeMax, singleFileSizeMax); this.error = wr.getRequestProcessingError(); r = wr; } else { r = request; this.error = null; } this.request = r; }