List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:AdminPackage.AdminAddProductController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w.j a va2 s .c om*/ * @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 { HProductDao pDao = new HProductDao(); Product product = new Product(); Categories c = new Categories(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); switch (name) { case "productName": product.setProductName(value); break; case "productDesc": product.setProductDescription(value); break; case "productPrice": product.setProductPrice(Float.parseFloat(value)); break; case "productQuantityAvailable": product.setProductQuntityavailable(Integer.parseInt(value)); break; case "productQuantitySold": product.setProductQuntitysold(Integer.parseInt(value)); break; case "productCategory": c.setIdcategory(Integer.parseInt(value)); product.setCategories(c); break; } } else { if (!item.isFormField()) { item.write(new File("C:/images/" + item.getName())); product.setProductImg(item.getName()); } } } } catch (FileUploadException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } pDao.insert(product); /* PrintWriter out = response.getWriter(); out.write("Done");*/ response.sendRedirect("/WebProjectServletJsp/AdminProductController"); }
From source file:prop_add_serv.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . ja va2s.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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); HttpSession hs = request.getSession(); PrintWriter out = response.getWriter(); try { if (hs.getAttribute("user") != null) { Login ln = (Login) hs.getAttribute("user"); System.out.println(ln.getUId()); String pradd1 = ""; String pradd2 = ""; String prage = ""; String prarea = ""; String prbhk = ""; String prdescrip = ""; String prprice = ""; String prcity = ""; String prstate = ""; String prname = ""; String prtype = ""; String prfarea = ""; String prphoto1 = ""; String prphoto2 = ""; String prphoto3 = ""; String prphoto4 = ""; // // 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(); if (fieldName.equals("pname")) { //getting value of field prname = fileItem.getString(); System.out.println(prname); } else if (fieldName.equals("price")) { //getting value of field prprice = fileItem.getString(); System.out.println(prprice); } else if (fieldName.equals("city")) { prcity = fileItem.getString(); System.out.println(prcity); } else if (fieldName.equals("state")) { prstate = fileItem.getString(); System.out.println(prstate); } else if (fieldName.equals("area")) { prarea = fileItem.getString(); System.out.println(prarea); } else if (fieldName.equals("pbhk")) { prbhk = fileItem.getString(); System.out.println(prbhk); } else if (fieldName.equals("pdescription")) { prdescrip = fileItem.getString(); System.out.println(prdescrip); } else if (fieldName.equals("ptype")) { prtype = fileItem.getString(); System.out.println(prtype); } else if (fieldName.equals("paddress1")) { pradd1 = fileItem.getString(); System.out.println(pradd1); } else if (fieldName.equals("paddress2")) { pradd2 = fileItem.getString(); System.out.println(pradd2); } else if (fieldName.equals("page")) { prage = fileItem.getString(); System.out.println(prage); } else if (fieldName.equals("pfarea")) { prfarea = fileItem.getString(); System.out.println(prfarea); } } else { String fieldName = fileItem.getFieldName(); if (fieldName.equals("photo1")) { //getting name of file prphoto1 = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring // String extension=prphoto.substring(prphoto.indexOf(".")+1,prphoto.length());; //rename file...concate name and extension //prphoto=prname+"."+extension; //System.out.println(prphoto); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // FOR UBUNTU add GETRESOURCE and GETPATH // String filePath = this.getServletContext().getResource("/images").getPath() + "\\"; fileItem.write(new File(fp + prphoto1)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 2 else if (fieldName.equals("photo2")) { prphoto2 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto2)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 3 else if (fieldName.equals("photo3")) { prphoto3 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto3)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 4 else if (fieldName.equals("photo4")) { prphoto4 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto4)); } catch (Exception ex) { out.println(ex.toString()); } } } } SessionFactory sf = NewHibernateUtil.getSessionFactory(); Session ss = sf.openSession(); Transaction tr = ss.beginTransaction(); String op = ""; Criteria cr = ss.createCriteria(StateMaster.class); cr.add(Restrictions.eq("sId", Integer.parseInt(prstate))); ArrayList<StateMaster> ar = (ArrayList<StateMaster>) cr.list(); if (ar.isEmpty()) { } else { StateMaster sm = ar.get(0); op = sm.getSName(); } String city = ""; Criteria cr2 = ss.createCriteria(CityMaster.class); cr2.add(Restrictions.eq("cityId", Integer.parseInt(prcity))); ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>) cr2.list(); System.out.println("----------" + ar2.size()); if (ar2.isEmpty()) { } else { city = ar2.get(0).getCityName(); System.out.println("-------" + city); } String area = ""; Criteria cr3 = ss.createCriteria(AreaMaster.class); cr3.add(Restrictions.eq("areaId", Integer.parseInt(prarea))); ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>) cr3.list(); System.out.println("----------" + ar3.size()); if (ar3.isEmpty()) { } else { area = ar3.get(0).getAreaName(); System.out.println("-------" + area); } PropDetail pd = new PropDetail(); pd.setUId(ln); pd.setPAge(Integer.parseInt(prage)); pd.setPBhk(prbhk); pd.setPDescription(prdescrip.trim()); pd.setPAdd1(pradd1); pd.setPAdd2(pradd2); pd.setPPrice(Integer.parseInt(prprice)); pd.setPCity(city); pd.setPState(op); pd.setPArea(area); pd.setPName(prname); pd.setPType(prtype); pd.setPImg1(prphoto1); System.out.println(prphoto1); System.out.println(prphoto2); pd.setPImg2(prphoto2); pd.setPImg3(prphoto3); pd.setPImg4(prphoto4); pd.setPFloor(Integer.parseInt(prfarea)); ss.save(pd); tr.commit(); RequestDispatcher rd = request.getRequestDispatcher("property_search_1.jsp"); rd.forward(request, response); } } catch (HibernateException e) { out.println(e.getMessage()); } }
From source file:com.jflyfox.modules.filemanager.FileManager.java
public FileManager(HttpServletRequest request) { // get document root like in php String documentRoot = PathKit.getWebRootPath() + "/"; // get uploaded file list FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from w w w. j a va 2 s. c o m if (ServletFileUpload.isMultipartContent(request)) files = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } this.properties.put("Date Created", null); this.properties.put("Date Modified", null); this.properties.put("Height", null); this.properties.put("Width", null); this.properties.put("Size", null); if (getConfig("doc_root") != null) this.fileRoot = getConfig("doc_root"); else this.fileRoot = documentRoot; dateFormat = new SimpleDateFormat(getConfig("date")); this.setParams(); loadLanguageFile(); }
From source file:it.swim.servlet.profilo.azioni.RilasciaFeedBackServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)// w w w . ja v a 2 s.c o m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi // ad una classe di utilita' String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request); List<FileItem> items; int punteggioFeedBack = 0; String commento = ""; // se e' null e' perche' l'utente non e' collegato e allora devo fare il // redirect alla home if (emailUtenteCollegato == null) { response.sendRedirect("../../home"); return; } try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). // ... (do your job here) if (item.getFieldName().equals("punteggioFeedBack")) { punteggioFeedBack = Integer.parseInt(item.getString().trim()); } if (item.getFieldName().equals("commentoFeedBack")) { commento = item.getString().trim(); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (punteggioFeedBack < 1 || punteggioFeedBack > 5) { request.setAttribute("erroreNelPunteggio", "Il punteggio deve essere compreso tra 1 e 5"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); return; } if (commento.isEmpty()) { commento = "Non ci sono commenti rilasciati"; } try { collab.rilasciaFeedback(idCollaborazione, punteggioFeedBack, commento); } catch (LoginException e) { // TODO Auto-generated catch block request.setAttribute("erroreNelPunteggio", "Collaborazione a cui aggiungere il feedBack non trovata"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); return; } request.setAttribute("feedBackRilasciato", "Feedback rilasciato con successo"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp") .forward(request, response); }
From source file:com.primeleaf.krystal.web.action.console.CheckInDocumentAction.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); try {//from ww w .j a va 2 s .c om if ("POST".equalsIgnoreCase(request.getMethod())) { String errorMessage; String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += loggedInUser.getUserName() + "_" + session.getId(); String revisionId = "", comments = "", fileName = "", ext = "", version = ""; int documentId = 0; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest((HttpServletRequest) request); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener Iterator iter = items.iterator(); FileItem item = null; File file = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("documentid")) { try { documentId = Integer.parseInt(value); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } } else if (name.equals("revisionid")) { revisionId = value; } else if (name.equals("txtNote")) { comments = value; } else if ("version".equalsIgnoreCase(name)) { version = value; } } else { fileName = item.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); file = new File(tempFilePath + "." + ext); item.write(file); } } iter = null; Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid check-in"); return (new CheckInDocumentView(request, response)); } revisionId = document.getRevisionId(); DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCheckin()) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied"); return (new CheckInDocumentView(request, response)); } if (file.length() <= 0) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new CheckInDocumentView(request, response)); } if (file.length() > documentClass.getMaximumFileSize()) { //code for checking maximum size of document in a class request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document size exceeded"); return (new CheckInDocumentView(request, response)); } String indexValue = ""; String indexName = ""; Hashtable indexRecord = new Hashtable(); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem fileItem = (FileItem) itemsIterator.next(); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } if (IndexDefinition.INDEXTYPE_NUMBER .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } else if (IndexDefinition.INDEXTYPE_DATE .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking maximum length of index field errorMessage = "Document index length exceeded. Index Name :" + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } indexRecord.put(indexName, indexValue); } } fileItem = null; } // while iter itemsIterator = null; } // while indexDefinitionItr CheckedOutDocument checkedOutDocument = new CheckedOutDocument(); checkedOutDocument.setDocumentId(documentId); // Added by Viral Visaria. For the Version Control minor and major. // In minor revision increment by 0.1. (No Changes required for the minor revision its handled in the core logic) // In major revision increment by 1.0 (Below chages are incremented by 0.9 and rest 0.1 will be added in the core logic. (0.9 + 0.1 = 1.0) double rev = Double.parseDouble(revisionId); if ("major".equals(version)) { rev = Math.floor(rev); rev = rev + 0.9; revisionId = String.valueOf(rev); } checkedOutDocument.setRevisionId(revisionId); checkedOutDocument.setUserName(loggedInUser.getUserName()); RevisionManager revisionManager = new RevisionManager(); revisionManager.checkIn(checkedOutDocument, documentClass, indexRecord, file, comments, ext, loggedInUser.getUserName()); //revision id incremented by 0.1 for making entry in audit log rev += 0.1; revisionId = String.valueOf(rev); //add to audit log AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CHECKIN, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "Document ID : " + documentId + " Revision ID :" + revisionId, "Checked In")); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Document checked in successfully"); return (new CheckInDocumentView(request, response)); } int documentId = 0; try { documentId = Integer.parseInt( request.getParameter("documentid") != null ? request.getParameter("documentid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (!Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid checkin"); return (new CheckInDocumentView(request, response)); } DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); LinkedHashMap<String, String> documentIndexes = IndexRecordManager.getInstance() .readIndexRecord(documentClass, documentId, document.getRevisionId()); request.setAttribute("DOCUMENTCLASS", documentClass); request.setAttribute("DOCUMENT", document); request.setAttribute("DOCUMENTINDEXES", documentIndexes); } catch (Exception e) { e.printStackTrace(); } return (new CheckInDocumentView(request, response)); }
From source file:Game_DataS.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w.j a v a2 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, ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { String datetime = null, field = null, visitors = null, hteamname = null, fteamname = null; Integer Ivisitors = null; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); //First do the Proccesing of data . Data received from URL-POST method.. // // Check that we have a file upload request boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //Parse the request to get file items. List<FileItem> fields = upload.parseRequest(request); // Process the uploaded file items Iterator<FileItem> it = fields.iterator(); //loop while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); //Form Field if (isFormField) { String tmp = fileItem.getFieldName(); if (tmp.equals("datetime")) { datetime = fileItem.getString(); } else if (tmp.equals("field")) { field = fileItem.getString(); } else if (tmp.equals("visitors")) { visitors = fileItem.getString(); //cast to Integer Ivisitors = Integer.parseInt(visitors); } else if (tmp.equals("hteamname")) { hteamname = fileItem.getString(); } else if (tmp.equals("fteamname")) { fteamname = fileItem.getString(); } } //extracted all STATIC INFO, now go to txt;s else { //Call Method that parses txt and do the inserts TXT_FILES_PROCESS(fileItem.getString(), fileItem.getFieldName(), out, hteamname, fteamname, datetime, field, Ivisitors); } } //------------------------------------- out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>EuroLeague Page</title>"); out.println("</head>"); out.println("<body>"); out.println("<div><h1>Successfull Registry in DataBase !!</h1>"); out.println("<br></br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Home Page for further action ---> <input type=\"submit\" value=\"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (FileUploadException FUE) { System.out.println("debugg " + FUE.getLocalizedMessage()); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title> EuroLeague Page</title>"); out.println("</head>"); out.println("<body style = \"background-color: #720;\">"); out.println( "<div><h1> Sorry...Something went wrong with the TXT uploading.Please go to home page and try again uploading a valid txt !!</h1>"); out.println("<br> </br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Press here -> <input type = \"submit\" value = \"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (IOException IOE) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title> EuroLeague Page</title>"); out.println("</head>"); out.println("<body style = \"background-color: #720;\">"); out.println( "<div><h1> Sorry...Something went wrong.Maybe a network error.Please go to home page !!</h1>"); out.println("<br> </br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Press here -> <input type = \"submit\" value = \"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } }
From source file:com.manning.cmis.theblend.servlets.AddServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // we expected content -> return to add page dispatch("add.jsp", "Add something new. The Blend.", request, response); }/*w ww . jav a 2s.com*/ Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String parentId = null; String parentPath = null; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_PARENT_ID.equalsIgnoreCase(name)) { parentId = item.getString(); } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) { parentPath = item.getString(); } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) { properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString()); } } else { String name = item.getName(); if (name == null) { name = "file"; } else { // if the browser provided a path instead of a file name, // strip off the path int x = name.lastIndexOf('/'); if (x > -1) { name = name.substring(x + 1); } x = name.lastIndexOf('\\'); if (x > -1) { name = name.substring(x + 1); } name = name.trim(); if (name.length() == 0) { name = "file"; } } properties.put(PropertyIds.NAME, name); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!"); } try { // prepare the content stream ContentStream contentStream = null; try { String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // find the parent folder // (we don't deal with unfiled documents here) Folder parent = null; if (parentId != null) { parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } else { parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } // create the document try { newId = session.createDocument(properties, parent, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:com.boundlessgeo.geoserver.api.controllers.ApiController.java
protected ServletFileUpload newFileUpload() { DiskFileItemFactory diskFactory = new DiskFileItemFactory(); diskFactory.setSizeThreshold(1024 * 1024 * 256); // TODO: make this configurable return new ServletFileUpload(diskFactory); }
From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java
@RequestMapping(value = "", method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TextHtmlContentExceptionWrapper { try {//from ww w.j a va 2 s .co m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setAttachmentData(readInputStream(item.getInputStream())); attachment.setFilename(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } } catch (FileUploadException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code return; } for (int i = 0; i < attachments.size(); i++) { String description = formValues .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i); if (description == null) { throw new IllegalArgumentException( "Missing description " + i + 1 + " of " + attachments.size()); } attachments.get(0).setDescription(description); } TaskHandle taskHandle = getTaskHandle(formValues); UploadResult result = doUpload(response, attachments, taskHandle); response.setContentType("text/html"); response.getWriter() .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;//from w w w.java 2 s . com Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { 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("/var/lib/tomcat7/webapps/www_term_project/temp/")); 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.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(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { 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); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }