List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w ww. ja va 2 s . c om*/ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String vocabName = null; String name = "nothing"; String status = "Upload failed "; try { if (ServletFileUpload.isMultipartContent(request)) { name = "isMultiPart"; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ InputStream input = null; Iterator it = fileItemsList.iterator(); String result = ""; String vocabs = null; while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: " + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: " + fileItem.getString() + "\n"; if (fileItem.isFormField()) { /* The file item contains a simple name-value pair of a form field */ if (fileItem.getFieldName().equals("vocab-name")) vocabName = fileItem.getString(); else if (fileItem.getFieldName().equals("vocab-terms")) vocabs = fileItem.getString(); } else { @SuppressWarnings("unused") String content = "nothing"; /* The file item contains an uploaded file */ /* Create new File object File uploadedFile = new File("test.txt"); if(!uploadedFile.exists()) uploadedFile.createNewFile(); // Write the uploaded file to the system fileItem.write(uploadedFile); */ name = fileItem.getName(); content = fileItem.getContentType(); input = fileItem.getInputStream(); } } //MetaDbHelper.note(result); if (vocabName != null) { Set<String> vocabList = new TreeSet<String>(); if (input != null) { Scanner fileSc = new Scanner(input); while (fileSc.hasNextLine()) { String vocabEntry = fileSc.nextLine(); vocabList.add(vocabEntry.trim()); } HttpSession session = request.getSession(false); if (session != null) { String userName = (String) session.getAttribute("username"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User " + userName + " created vocab " + vocabName); } status = "Vocab name: " + vocabName + ". File name: " + name + "\n"; } else { // status = "Form is not multi-part"; // vocabName = request.getParameter("vocab-name"); // String vocabs = request.getParameter("vocab-terms"); MetaDbHelper.note(vocabs); for (String vocab : vocabs.split("\n")) vocabList.add(vocab); } if (!vocabList.isEmpty()) { if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList)) status = "Vocab " + vocabName + " created successfully"; else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList)) status = "Vocab " + vocabName + " updated successfully "; else status = "Vocab " + vocabName + " cannot be updated/created"; } } } } catch (Exception e) { MetaDbHelper.logEvent(e); } MetaDbHelper.note(status); out.print(status); out.flush(); }
From source file:it.swim.servlet.profilo.azioni.RicerchePerUtentiLoggatiServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */// w ww . j av a 2 s . com protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<FileItem> items; String nome = new String(); String cognome = new String(); String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request); List<Abilita> abilitaRicercate = new ArrayList<Abilita>(); List<Utente> risultatoRicerca = new ArrayList<Utente>(); boolean soloAmici = false; ricerca = false; 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("nomeUtente")) { nome = item.getString().trim(); } if (item.getFieldName().equals("cognomeUtente")) { cognome = item.getString().trim(); } if (item.getFieldName().equals("abilita")) { abilitaRicercate.add(registrazione.getAbilitaByNome(item.getString())); } if (item.getFieldName().equals("soloAmici")) { soloAmici = true; } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (tipoRicerca.equals("aiuto")) { try { risultatoRicerca = gestioneRicerche.ricercaAiuto(abilitaRicercate, (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request)); if (soloAmici == true) { List<Utente> amiciUtente = gestioneAmicizie.getAmici(emailUtenteCollegato); for (int i = 0; i < risultatoRicerca.size(); i++) { if (!(amiciUtente.contains(risultatoRicerca.get(i)))) { risultatoRicerca.remove(i); i--; } } } } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("abilita", gestioneRicerche.insiemeAbilitaGenerali()); request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); request.setAttribute("tipoRicerca", tipoRicerca); } else if (tipoRicerca.equals("aiutoVisitatore")) { try { risultatoRicerca = gestioneRicerche.ricercaAiutoVisitatore(abilitaRicercate); } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("abilita", gestioneRicerche.insiemeAbilitaGenerali()); request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); request.setAttribute("tipoRicerca", tipoRicerca); } else { try { risultatoRicerca = gestioneRicerche.ricercaUtenti(nome, cognome, (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request)); } catch (RicercheException e) { // TODO Auto-generated catch block e.printStackTrace(); } ricercaGiaEffettuata = true; request.setAttribute("utenti", risultatoRicerca); if (risultatoRicerca.size() > 0) ricerca = true; request.setAttribute("risultatoRicerca", ricerca); request.setAttribute("tipoRicerca", tipoRicerca); request.setAttribute("ricercaGiaEffettuata", ricercaGiaEffettuata); } getServletConfig().getServletContext().getRequestDispatcher("/jsp/ricerche.jsp").forward(request, response); }
From source file:kotys.monika.MenuCreatorJSP.LoadData.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w .j av a2s . 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 { // Check that we have a file upload request request.setCharacterEncoding("UTF-8"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); ArrayList<String> files = new ArrayList<String>(); 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); try { // Parse the request List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadFolder + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory item.write(uploadedFile); files.add(filePath); } } // displays done.jsp page after upload finished request.getSession().setAttribute("uploadedFiles", files); processRequest(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { Logger.getLogger(LoadData.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.apt.ajax.controller.AjaxUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j a v a 2s . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload"; Gson gson = new Gson(); MessageBean messageBean = new MessageBean(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ File x = new File(uploadDir); if (!x.exists()) { x.mkdir(); } boolean isMultiplePart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (!isMultiplePart) { } else { List items = null; try { items = upload.parseRequest(request); if (items != null) { Iterator iterator = items.iterator(); String assignmentId = ""; String stuid = ""; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName.equals("assignmentid")) { assignmentId = item.getString(); File c = new File(uploadDir + File.separator + assignmentId); if (!c.exists()) { c.mkdir(); } uploadDir = c.getPath(); if (request.getSession().getAttribute("studentId") != null) { stuid = request.getSession().getAttribute("studentId").toString(); File stuDir = new File(uploadDir + File.separator + stuid); if (!stuDir.exists()) { stuDir.mkdir(); } uploadDir = stuDir.getPath(); } } } else { String itemname = item.getName(); if (itemname == null || itemname.equals("")) { } else { String filename = FilenameUtils.getName(itemname); File f = new File(uploadDir + File.separator + filename); String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload" + Pattern.quote(File.separator)); String save = split[split.length - 1]; if (assignmentId != null && !assignmentId.equals("")) { if (stuid != null && !stuid.equals("")) { } else { Assignment assignment = new AssignmentFacade() .findAssignment(Integer.parseInt(assignmentId)); assignment.setUrl(save); new AssignmentFacade().updateAssignment(assignment); } } item.write(f); messageBean.setStatus(0); messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded"); } } } } gson.toJson(messageBean, out); } catch (Exception ex) { messageBean.setStatus(1); messageBean.setMessage(ex.getMessage()); gson.toJson(messageBean, out); } } } catch (Exception ex) { Logger.getLogger(AjaxUpload.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aspectran.web.support.multipart.inmemory.MemoryMultipartFormDataParser.java
/** * Parse form fields and file items./*from w w w. jav a 2 s . com*/ * * @param fileItemListMap the file item list map * @param requestAdapter the request adapter */ private void parseMultipartParameters(Map<String, List<FileItem>> fileItemListMap, RequestAdapter requestAdapter) { String encoding = requestAdapter.getEncoding(); MultiValueMap<String, String> parameterMap = new LinkedMultiValueMap<>(); MultiValueMap<String, FileParameter> fileParameterMap = new LinkedMultiValueMap<>(); for (Map.Entry<String, List<FileItem>> entry : fileItemListMap.entrySet()) { String fieldName = entry.getKey(); List<FileItem> fileItemList = entry.getValue(); if (fileItemList != null && !fileItemList.isEmpty()) { for (FileItem fileItem : fileItemList) { if (fileItem.isFormField()) { String value = getString(fileItem, encoding); parameterMap.add(fieldName, value); } else { String fileName = fileItem.getName(); // Skip file uploads that don't have a file name - meaning that // no file was selected. if (StringUtils.isEmpty(fileName)) { continue; } boolean valid = FilenameUtils.isValidFileExtension(fileName, allowedFileExtensions, deniedFileExtensions); if (!valid) { continue; } MemoryMultipartFileParameter fileParameter = new MemoryMultipartFileParameter(fileItem); fileParameterMap.add(fieldName, fileParameter); if (log.isDebugEnabled()) { log.debug("Found multipart file [" + fileParameter.getFileName() + "] of size " + fileParameter.getFileSize() + " bytes, stored " + fileParameter.getStorageDescription()); } } } } } requestAdapter.putAllParameters(parameterMap); requestAdapter.putAllFileParameters(fileParameterMap); }
From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java
/** * This API is used to process uploaded file and unzip file in export-batch-folder . * // w ww. j a v a2 s . co m * @param upload {@link ServletFileUpload} uploaded file. * @param req {@link HttpServletRequest}. * @param printWriter {@link PrintWriter}. * @param parentDirPath {@link String} to create absolute unzip directory path. * @return {@link File} temporary file after unzip. */ private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req, final PrintWriter printWriter, final String parentDirPath) { String tempUnZipDir = ""; String zipFileName = ""; String zipPathname = ""; File tempZipFile = null; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) { zipPathname = getZipPath(item, parentDirPath); zipFileName = getZipFileName(item); tempZipFile = copyItemContentInFile(item, zipPathname, printWriter); } } } catch (final FileUploadException e) { printWriter.write("Unable to read the form contents.Please try again."); } tempUnZipDir = parentDirPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempUnZipDir); } catch (final Exception e) { printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } return tempUnZipDir; }
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); }// ww w . j a v a2 s . c o m 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.gae.ImageUpServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); //ReturnValue value = new ReturnValue(); MemoryFileItemFactory factory = new MemoryFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); resp.setContentType("image/jpeg"); ServletOutputStream out = resp.getOutputStream(); try {/*from w w w. ja v a 2s . c om*/ List<FileItem> list = upload.parseRequest(req); //FileItem list = upload.parseRequest(req); for (FileItem item : list) { if (!(item.isFormField())) { filename = item.getName(); if (filename != null && !"".equals(filename)) { int size = (int) item.getSize(); byte[] data = new byte[size]; InputStream in = item.getInputStream(); in.read(data); ImagesService imagesService = ImagesServiceFactory.getImagesService(); Image newImage = ImagesServiceFactory.makeImage(data); byte[] newImageData = newImage.getImageData(); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); out.write(newImageData); out.flush(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(kind, skey); Blob blobImage = new Blob(newImageData); DirectBeans_textjson dbeans = new DirectBeans_textjson(); /* ?Date? */ //Entity entity = dbeans.setentity("add", kind, true, key, id, val); //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val); //Entity entity = value.entity; //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue(); DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val); Entity entity = eval.entity; /* ?Date */ //for(int i=0; i<id.length; i++ ){ // if(id[i].equals("image")){ // //filetitle = val[i]; // //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]); // } //} entity.setProperty("image", blobImage); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss"); sdf.setTimeZone(TimeZone.getTimeZone("JST")); entity.setProperty("moddate", sdf.format(date)); //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); ds.put(entity); out.println("? KEY:" + key); } } } } catch (FileUploadException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } }
From source file:com.esteban.cmms.maven.controller.Imagenes_Controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . ja va 2s . 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 { String btne = request.getParameter("btn"); if (btne == null) { try { HttpSession sesion = request.getSession(); sesion.removeAttribute("imagenes"); Usuarios user = (Usuarios) sesion.getAttribute("usuario"); FileItemFactory itemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(itemFactory); String btn = null; Maquinas m = new Maquinas(); List<FileItem> items = upload.parseRequest(request); Imagenes pojo = new Imagenes(); pojo.setUserAction(user.getNombre()); for (FileItem item : items) { if (!item.isFormField()) { String contentType = item.getContentType(); if (!contentType.equals("image/png")) { //|| !contentType.equals("image/jpg") continue; } File img = new File( "/home/esteban/NetBeansProjects/" + "CMMS-Maven/src/main/webapp/Imagenes/images_cli", new Date() + item.getName()); item.write(img); pojo.setImagen(img.getName()); } if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("maquina")) { int idm = Integer.parseInt(item.getString()); System.out.println("Maquina"); m.setId(idm); pojo.setMaquinas(m); } else if (item.getFieldName().equalsIgnoreCase("btn")) { System.out.println("Guardar cambios"); btn = item.getString().replaceAll("\\s", ""); } else if (item.getFieldName().equalsIgnoreCase("id")) { System.out.println("id imagen"); pojo.setId(Integer.parseInt(item.getString())); } } } pojo.setEstado("Activo"); System.out.println("ste es el boton" + btn); if (btn.equalsIgnoreCase("actualizar")) { new Imagenes_Model().updateImagen(pojo); } else { new Imagenes_Model().addImagen(pojo); } response.sendRedirect("Imagenes"); } catch (FileUploadException ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } } else { String btn = btne.replaceAll("\\s", ""); if (btn.equalsIgnoreCase("imagenes")) { Imagenes_Model model = new Imagenes_Model(); HttpSession sesion = request.getSession(); String valor = request.getParameter("valor"); List<Imagenes> result = new ArrayList<Imagenes>(); if (valor.equalsIgnoreCase("activo")) { try { result = model.getAllImagenes(); sesion.setAttribute("imagenes", result); sesion.setAttribute("maquinas", new Maquinas_Model().getAllMaquinas()); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes"); } else if (valor.equalsIgnoreCase("inactivo")) { try { result = model.listNoActive(); sesion.setAttribute("imagenes", result); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes/archivados.jsp"); } } else if (btn.equalsIgnoreCase("estado")) { System.out.println("Definicin de estado"); System.out.println("Nuevo estado: " + request.getParameter("estado")); Usuarios user = (Usuarios) request.getSession().getAttribute("usuario"); try { new Imagenes_Model().estadoImagen(request.getParameter("estado"), Integer.parseInt(request.getParameter("id")), user.getNombre()); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } System.out.println("Estado definido con xito"); response.sendRedirect("Imagenes"); } } }
From source file:com.controller.changeLogo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww. java 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 */ @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(); getSqlMethodsInstance().session = request.getSession(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, uploadType = null; RequestDispatcher request_dispatcher = null; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.USER_LOGO; // 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()) { fieldName = fi.getFieldName(); if (fieldName.equals("upload")) { uploadType = fi.getString(); } } else { // Get the uploaded file parameters fieldName = fi.getFieldName(); fileName = fi.getName(); Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID"); uploadPath = uploadPath + File.separator + UID + File.separator + "logo"; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = Str + "_" + UID + ".jpeg"; fileName = fileName + "_" + UID; getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); if (uploadType.equals("update")) { String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID); String filePath_to_delete = uploadPath + File.separator + file_name_to_delete; File deletefile = new File(filePath_to_delete); deletefile.delete(); } filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); getSqlMethodsInstance().updateUsers(UID, fileName); out.println("Uploaded Filename: " + filePath + "<br>"); response.sendRedirect(request.getContextPath() + "/settings.jsp"); } } } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); getSqlMethodsInstance().closeConnection(); } }