List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. 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;//w w w .j av a2 s . c o m 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:eml.studio.server.file.FileUploadServlet.java
/** * save file upload to server/* w w w . ja v a2s .c om*/ * @param request HttpServletRequest * @param response HttpServletResponse * @throws ServletException */ public void saveUploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = null; List items_findId = null; try { items = upload.parseRequest(request); items_findId = items; } catch (FileUploadException ex) { ex.printStackTrace(); } String ID = new String(); Iterator iter_findId = items_findId.iterator(); while (iter_findId.hasNext()) { FileItem item_findId = (FileItem) iter_findId.next(); if (item_findId.isFormField()) { String fieldName = item_findId.getFieldName(); String fieldValue; try { fieldValue = item_findId.getString("UTF-8"); if ("Fileuuid".equals(fieldName)) { ID = Constants.MODULE_PATH + "/" + fieldValue; } else ID = Constants.DATASET_PATH + "/" + fieldValue; logger.info("[UUID]:" + fieldName + ":" + ID); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { InputStream in; try { in = item.getInputStream(); if (item.getName().endsWith(".zip")) { unZipFiles(in, ID); HDFSIO.uploadfile("/" + ID + "/", item, item.getName()); } else { if (ID.contains("Data")) { HDFSIO.uploadfile("/" + ID + "/", item, ID.split("Data")[1]); } else HDFSIO.uploadfile("/" + ID + "/", item, item.getName()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
From source file:com.kk.dic.action.Upload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); out = response.getWriter();//from w w w .j a va 2s . co m Connection con; PreparedStatement pstm = null; String fname = ""; String keyword = ""; String cd = ""; String a = (String) request.getSession().getAttribute("email"); System.out.println("User Name : " + a); try { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); out.print("one"); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); if (fileItem.getFieldName().equals("name")) { fname = fileItem.getString(); System.out.println("File Name" + fname); } else if (fileItem.getFieldName().equals("keyword")) { keyword = fileItem.getString(); System.out.println("File Keyword" + keyword); } else { } boolean isFormField = fileItem.isFormField(); if (isFormField) { } else { out.print("one"); try { con = Dbconnection.getConnection(); pstm = con.prepareStatement( "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)"); out.println("getD " + fileItem.getName()); String str = getStringFromInputStream(fileItem.getInputStream()); // secretkey generating KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); System.out.println("secret key:" + secretKey); //converting secretkey to String byte[] be = secretKey.getEncoded();//encoding secretkey String skey = Base64.encode(be); System.out.println("converted secretkey to string:" + skey); String cipher = new encryption().encrypt(str, secretKey); System.out.println(str); //for get extension from given file String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.')); System.out.println("File Extension" + b); pstm.setBinaryStream(1, fileItem.getInputStream()); pstm.setString(2, keyword); pstm.setString(3, b); pstm.setString(4, fname); pstm.setDate(5, getCurrentDate()); pstm.setString(6, a); pstm.setLong(7, fileItem.getSize()); pstm.setString(8, cipher); pstm.setString(9, "0"); pstm.setString(10, skey); /*Cloud Start*/ File f = new File("D:/" + fileItem.getName()); out.print("<br/>" + f.getName()); FileWriter fw = new FileWriter(f); fw.write(cipher); fw.close(); Ftpcon ftpcon = new Ftpcon(); ftpcon.upload(f, fname); /*Cloud End*/ int i = pstm.executeUpdate(); if (i == 1) { response.sendRedirect("upload.jsp?msg=success"); } else { response.sendRedirect("upload.jsp?msgg=failed"); } con.close(); } catch (Exception e) { out.println(e); } } } } catch (Exception ex) { out.print(ex); Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } } finally { out.close(); } }
From source file:controller.StudentController.java
@RequestMapping(value = "/add", method = RequestMethod.POST) public String addorchange(HttpServletRequest request) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // int mssv = Integer.parseInt(request.getParameter("mssv")); // String tensv = request.getParameter("tensv"); // String ngaysinh = request.getParameter("ngaysinh"); // String ngaydi = request.getParameter("ngaydi"); // String que = request.getParameter("que"); // String lop = request.getParameter("lop"); // String khoa = request.getParameter("khoa"); // int sdt = Integer.parseInt(request.getParameter("sdt")); // int maphong = Integer.parseInt(request.getParameter("roomnum")); // int makhu = Integer.parseInt(request.getParameter("roomregion")); int mssv = 0; String tensv = null;// ww w. jav a 2 s . c o m String ngaysinh = null; String ngaydi = null; String que = null; String lop = null; String khoa = null; int sdt = 0; int maphong = 0; int makhu = 0; FileItem f = null; String fName = null; try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("mssv")) { mssv = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("tensv")) { tensv = item.getString(); } if (item.getFieldName().equals("ngaysinh")) { ngaysinh = item.getString(); } if (item.getFieldName().equals("ngaydi")) { ngaydi = item.getString(); } if (item.getFieldName().equals("que")) { que = item.getString(); } if (item.getFieldName().equals("lop")) { lop = item.getString(); } if (item.getFieldName().equals("khoa")) { khoa = item.getString(); } if (item.getFieldName().equals("sdt")) { sdt = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("roomnum")) { maphong = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("roomregion")) { makhu = Integer.parseInt(item.getString()); } if (!item.isFormField()) { f = item; fName = new File(item.getName()).getName(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } RoomRegion region = new RoomRegion(makhu, ""); Room room = new Room(maphong, region, 0, 0, null, null); if (room.checkRoom()) { Student student = new Student(mssv, tensv, ngaysinh, que, lop, khoa, room, sdt, ngaydi, fName); request.setAttribute("roomnum", new Room().roomList()); request.setAttribute("roomregion", new RoomRegion().regionList()); try { if (student.add() >= 3) { String path = request.getServletContext().getRealPath("/"); String UPLOAD_DIRECTORY = path + "/static/uploads"; File dir = new File(UPLOAD_DIRECTORY); dir.mkdirs(); File file = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + fName); f.write(file); System.out.println(file.getPath()); request.setAttribute("message", "Thm thnh cng!"); } else { request.setAttribute("message", "Khng thm c, Sinh vin ny tn ti!"); } } catch (SQLException ex) { Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { request.setAttribute("message", "Phng ny hin y!"); } request.setAttribute("id", "add"); return SVManager(request); }
From source file:com.osbitools.ws.shared.prj.web.EntityUtilsMgrWsSrvServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w ww . j ava2 s. c o m*/ super.doPost(req, resp); } catch (ServletException e) { if (e.getCause().getClass().equals(WsSrvException.class)) { // Authentication failed checkSendError(req, resp, (WsSrvException) e.getCause()); return; } else { throw e; } } // Get DsMap name String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM); // Check if rename required try { if (!ServletFileUpload.isMultipartContent(req)) { checkSendError(req, resp, 200, "Request is not multipart"); return; } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory(req)); InputStream in = null; List<FileItem> items; try { items = upload.parseRequest(req); } catch (FileUploadException e) { checkSendError(req, resp, 201, "Error parsing request", null, e); return; } for (FileItem fi : items) { if (!fi.isFormField()) { in = fi.getInputStream(); break; } } if (in == null) { checkSendError(req, resp, 202, "File Multipart section is not found"); return; } boolean minified = isMinfied(req); printJson(resp, "{" + Utils.getCRT(minified) + "\"entity\":" + Utils.getSPACE(minified) + getEntityUtils(req).create(getPrjRootDir(req), name, in, false, minified) + "}"); in.close(); } catch (WsSrvException e) { checkSendError(req, resp, e); } }
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 ww.j a v a 2s . co m 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:Controller.ControllerImage.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from www . java 2s. 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); 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:com.seer.datacruncher.profiler.spring.FileUploadController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request filePath = this.servletContext.getInitParameter("file-upload"); isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { return null; }//w w w . jav a2 s . com 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(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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String 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.print("{success: true, file: \"" + fileName + "\"}"); // out.println("{\"file\": " + fileName + "}"); } } } catch (Exception ex) { System.out.println(ex); } return null; }
From source file:cust_photo_upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . jav 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"); 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:controller.Upload.java
/** * Servlet implementation class UploadServlet *//*www . jav a 2 s .c om*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { 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 uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); String fileName = "", newname = ""; 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 = (String)session.getId() + new File(item.getName()).getName(); // String filePath = uploadFolder + File.separator + fileName; fileName = new File(item.getName()).getName(); newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf(".")); String filePath = uploadFolder + File.separator + newname; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory item.write(uploadedFile); } } userDao ud = new userDao(); ud.changeuserpic((int) session.getAttribute("userID"), newname); // displays done.jsp page after upload finished getServletContext().getRequestDispatcher("/done.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } }