List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.wakasta.tubes2.AddProductPost.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String item_data = ""; // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;//w w w .ja v a2 s .co m } 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:\\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(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); 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)); } item_data = Base64.encodeBase64String(fi.get()); fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); // out.println(file); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } catch (java.lang.Exception ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /* w w w.j a va2 s. c om*/ * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) { System.out.println("--- BEGIN DOPOST ---"); } response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) { System.out.println(currentDirPath); } String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } System.out.println("111111222111111111"); out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww . j a v a2 s. c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = response.getWriter(); HttpSession aSession = request.getSession(); try { Person pers = (Person) aSession.getAttribute("person"); String primaryKey = pers.getAccount().getEmail(); PersonManager aPerson = PersonManager.getInstance(); Person person = aPerson.getStudent(primaryKey); ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance(); out = response.getWriter(); String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula()); File subfolderFile = new File(studentSubfolderPath); if (!subfolderFile.exists()) { subfolderFile.mkdir(); } isMultipart = ServletFileUpload.isMultipartContent(request); String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String CVPath = "", ATPath = ""; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (fieldName.equals("cv")) { fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf"); CVPath = fileToStore.getAbsolutePath(); } else if (fieldName.equals("doc")) { fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf"); ATPath = fileToStore.getAbsolutePath(); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); } } if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) { message.setMessage("status", 1); } else { message.setMessage("status", 0); } aSession.setAttribute("message", message); response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp"); //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp"); //dispatcher.forward(request,response); } catch (Exception ex) { Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex); message.setMessage("status", -1); aSession.setAttribute("message", message); } finally { out.close(); } }
From source file:com.apt.ajax.controller.AjaxUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . ja v 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("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.skin.taurus.http.servlet.UploadServlet.java
public void upload(HttpRequest request, HttpResponse response) throws IOException { int maxFileSize = 1024 * 1024; String repository = System.getProperty("java.io.tmpdir"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(repository)); factory.setSizeThreshold(maxFileSize * 2); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setFileSizeMax(maxFileSize); servletFileUpload.setSizeMax(maxFileSize); try {/* w ww . ja v a 2s. co m*/ HttpServletRequest httpRequest = new HttpServletRequestAdapter(request); List<?> list = servletFileUpload.parseRequest(httpRequest); for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { if (logger.isDebugEnabled()) { logger.debug("Form Field: " + item.getFieldName() + " " + item.toString()); } } else if (!item.isFormField()) { if (item.getFieldName() != null) { String fileName = this.getFileName(item.getName()); String extension = this.getFileExtensionName(fileName); if (this.isAllowed(extension)) { try { this.save(item); } catch (Exception e) { e.printStackTrace(); } } item.delete(); } else { item.delete(); } } } } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:net.formio.upload.MultipartRequestPreprocessor.java
private void addSingleValueFile(RequestUploadedFile file, FileItem item) { List<RequestUploadedFile> list = new ArrayList<RequestUploadedFile>(); list.add(file);/* w w w.j av a 2 s. c o m*/ fileParams.put(item.getFieldName(), list); }
From source file:com.duroty.application.mail.actions.SendAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try {//from w w w . j a v a2s.c om boolean isMultipart = FileUpload.isMultipartContent(request); Mail mailInstance = getMailInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector attachments = new Vector(); //Parse the request List items = diskFileUpload.parseRequest(request); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("forwardAttachments")) { String[] aux = item.getString().split(":"); MailPartObj part = mailInstance.getAttachment(aux[0], aux[1]); attachments.addElement(part); } else { fields.put(item.getFieldName(), item.getString()); } } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); attachments.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } String body = ""; if (fields.get("taBody") != null) { body = (String) fields.get("taBody"); } else if (fields.get("taReplyBody") != null) { body = (String) fields.get("taReplyBody"); } Preferences preferencesInstance = getPreferencesInstance(request); Send sendInstance = getSendInstance(request); String mid = (String) fields.get("mid"); if (StringUtils.isBlank(mid)) { request.setAttribute("action", "compose"); } else { request.setAttribute("action", "reply"); } Boolean isHtml = null; if (StringUtils.isBlank((String) fields.get("isHtml"))) { isHtml = new Boolean(preferencesInstance.getPreferences().isHtmlMessage()); } else { isHtml = Boolean.valueOf((String) fields.get("isHtml")); } sendInstance.send(mid, Integer.parseInt((String) fields.get("identity")), (String) fields.get("to"), (String) fields.get("cc"), (String) fields.get("bcc"), (String) fields.get("subject"), body, attachments, isHtml.booleanValue(), Charset.defaultCharset().displayName(), (String) fields.get("priority")); } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFileParser.java
/** * Parses a list of multipart files and sends them to {@link MultiPartFileProcessor}. * @param fields a list of multipart files that will be processed * @return with the processing status message or "No file uploaded" when the list is empty * @throws IOException was thrown file parsing failed *//*from w w w . j a va 2s. c o m*/ public String parseMultiPartFiles(final List<FileItem> fields) throws IOException { String msg = ""; Iterator<FileItem> it = fields.iterator(); if (!fields.isEmpty() && it.hasNext()) { while (it.hasNext()) { FileItem fileItem = it.next(); if (!fileItem.isFormField()) { String uploadedFileName = fileItem.getName(); InputStream uploadedResource = fileItem.getInputStream(); String contentType = fileItem.getContentType(); String fieldName = fileItem.getFieldName(); msg += multiPartFileProcessor.processUploadedFile(uploadedResource, contentType, fieldName, uploadedFileName); } } } else { msg = "No file uploaded"; } return msg; }
From source file:com.GTDF.server.FileUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String rootDirectory = getServletConfig().getInitParameter("TRANSFORM_HOME"); String workDirectory = getServletConfig().getInitParameter("TRANSFORM_DIR"); String prefixDirectory = ""; boolean writeToFile = true; String returnOKMessage = "OK"; String username = ""; String authResult = ""; boolean isMultipart = ServletFileUpload.isMultipartContent(request); PrintWriter out = response.getWriter(); // Create a factory for disk-based file items if (isMultipart) { // We are uploading a file (deletes are performed by non multipart requests) FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {// w w w. ja v a 2 s . co m List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // Hidden field containing username - check authorization if (item.getFieldName().equals("username")) { username = item.getString(); String wikiDb = getServletConfig().getInitParameter("WIKIDB"); String wikiDbUser = getServletConfig().getInitParameter("WIKIDB_USER"); String wikiDbPassword = getServletConfig().getInitParameter("WIKIDB_PASSWORD"); String wikiNoAuth = getServletConfig().getInitParameter("NOAUTH"); // v1.5 Check parameter NOAUTH WikiUserImpl wikiUser = new WikiUserImpl(); authResult = wikiUser.wikiUserVerifyDb(username, wikiDb, wikiDbUser, wikiDbPassword, wikiNoAuth); if (authResult != "LOGGED") { out.print(authResult); return; } else new File(rootDirectory + workDirectory + '/' + username).mkdirs(); } // Hidden field containing file prefix to create subdirectory if (item.getFieldName().equals("prefix")) { prefixDirectory = item.getString(); new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory) .mkdirs(); prefixDirectory += '/'; } } else { if (writeToFile) { String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { fileName = FilenameUtils.getName(fileName); File uploadedFile = new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory + fileName); try { item.write(uploadedFile); String hostedOn = getServletConfig().getInitParameter("HOSTED_ON"); out.print("Infile at: " + hostedOn + workDirectory + '/' + username + '/' + prefixDirectory + fileName); } catch (Exception e) { e.printStackTrace(); } } } else { } } } } catch (FileUploadException e) { e.printStackTrace(); } } else { //Process a request to delete a file String[] paramValues = request.getParameterValues("uploadFormElement"); for (int i = 0; i < paramValues.length; i++) { String fileName = FilenameUtils.getName(paramValues[i]); File deleteFile = new File(rootDirectory + workDirectory + fileName); if (deleteFile.delete()) { out.print(returnOKMessage); } } } }
From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*w ww .j a va 2s . c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (fileSize < 30240) { String typeStr = request.getParameter("Type"); String currentPath = ""; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = FckeditorUtil.getNameWithoutExtension(fileName); String ext = FckeditorUtil.getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }