List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:mercury.DigitalMediaController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {/* w w w. j ava 2 s.c om*/ List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { Integer serial = (new DigitalMediaDAO()).uploadToDigitalMedia(item); String filename = item.getName(); if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/') + 1); } String id = serial + ":" + filename; String encodedId = new String(new Base64().encode(id.getBytes())); encodedId = encodedId.replaceAll("\\\\", "_"); if (serial != null && serial != 0) { response.getWriter().write("{success: true, id: \"" + encodedId + "\"}"); return; } } } } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().write("{success: false}"); } else { String decodedId = null; DigitalMediaDTO dto = null; try { String id = request.getParameter("id"); id = id.replaceAll("_", "\\\\"); decodedId = new String(new Base64().decode(id.getBytes())); String[] splitId = decodedId.split(":"); if (splitId.length == 2 && splitId[0].matches("^\\d+$")) { dto = (new DigitalMediaDAO()).getDigitalMedia(Integer.valueOf(splitId[0]), splitId[1]); } } catch (Exception e) { // dto should be null here } InputStream in = null; byte[] bytearray = null; int length = 0; String defaultFile = request.getParameter("default"); response.reset(); try { if (dto != null && dto.getIn() != null) { response.setContentType(dto.getMimeType()); response.setHeader("Content-Disposition", "filename=" + dto.getFileName()); length = dto.getLength(); in = dto.getIn(); } if (in == null && StringUtils.isNotBlank(defaultFile)) { String path = getServletContext().getRealPath("/"); File file = new File(path + defaultFile); length = (int) file.length(); in = new FileInputStream(file); } if (in != null) { bytearray = new byte[length]; int index = 0; OutputStream os = response.getOutputStream(); while ((index = in.read(bytearray)) != -1) { os.write(bytearray, 0, index); } in.close(); } else { response.getWriter().write("{success: false}"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{success: false}"); } response.flushBuffer(); } }
From source file:edu.byui.fb.AddImage.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww .j a v a2s . co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the DataBaseHandler DataBaseHandler dbh = DataBaseHandler.getInstance(); // Get information about the user currently logged in boolean logged = (boolean) request.getSession().getAttribute("logged"); String username = (String) request.getSession().getAttribute("username"); User user = dbh.getUser(username); // Are we currently logged in if (username != null && user != null && logged) { // Check to make sure the request is multipart if (ServletFileUpload.isMultipartContent(request)) { try { // Parse the request into FileItems List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); String title = ""; InputStream imageInputStream = null; // Loop through each item for (FileItem item : multipart) { // Are we dealing with a file or something different if (!item.isFormField()) { if (item.getFieldName().equals("image")) { imageInputStream = item.getInputStream(); } } else if (item.isFormField()) { if (item.getFieldName().equals("title")) { title = item.getString(); } } } // Was there a title? If not, give a fake title if (title.equals("")) { title = "No title"; } // Set up the image and add to the DataBase. Image image = new Image(title, imageInputStream); dbh.addImage(image, user); request.setAttribute("imageAdded", true); } catch (FileUploadException ex) { Logger.getLogger(AddImage.class.getName()).log(Level.SEVERE, null, ex); } } } else { // Was there an error? request.setAttribute("addedError", true); } // Go to admin.jsp request.getRequestDispatcher("LoadImages?dest=admin.jsp").forward(request, response); }
From source file:com.aquest.emailmarketing.web.controllers.ImportController.java
/** * Import list./* ww w .ja v a 2 s .c o m*/ * * @param model the model * @param request the request * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception * @throws ParserConfigurationException the parser configuration exception * @throws TransformerException the transformer exception * @throws ServletException the servlet exception * @throws FileUploadException the file upload exception */ @RequestMapping(value = "/importList", method = RequestMethod.POST) public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException, ParserConfigurationException, TransformerException, ServletException, FileUploadException { List<String> copypaste = new ArrayList<String>(); String listfilename = ""; String separator = ""; String broadcast_id = ""; String old_broadcast_id = ""; String listType = ""; EmailListForm emailListForm = new EmailListForm(); InputStream fileContent = null; List<FileItem> 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). String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName.equals("listType")) { listType = fieldValue; System.out.println(listType); } else if (fieldName.equals("copypaste")) { for (String line : fieldValue.split("\\n")) { copypaste.add(line); System.out.println(line); } } else if (fieldName.equals("listfilename")) { listfilename = fieldValue; } else if (fieldName.equals("separator")) { separator = fieldValue; } else if (fieldName.equals("broadcast_id")) { broadcast_id = fieldValue; } else if (fieldName.equals("old_broadcast_id")) { old_broadcast_id = fieldValue; } } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fileName = FilenameUtils.getName(item.getName()); fileContent = item.getInputStream(); } System.out.println(listfilename); System.out.println(separator); } int importCount = 0; if (listType.equals("copy")) { if (!copypaste.isEmpty()) { List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } else { // sta ako je prazno } } if (listType.equals("fromfile")) { List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } System.out.println(broadcast_id); model.addAttribute("importCount", importCount); model.addAttribute("emailListForm", emailListForm); Broadcast broadcast = broadcastService.getBroadcast(broadcast_id); System.out.println("Old broadcast: " + old_broadcast_id); if (!old_broadcast_id.isEmpty()) { model.addAttribute("old_broadcast_id", old_broadcast_id); } String message = null; if (broadcast.getBcast_template_id() != null) { message = "template"; } model.addAttribute("message", message); model.addAttribute("broadcast_id", broadcast_id); return "importlistreport"; }
From source file:com.eufar.asmm.server.UploadFunction.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadFunction - the function started"); response.setContentType("text/html;charset=UTF-8"); response.addHeader("Cache-Control", "no-cache,no-store"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from ww w. j a v a2 s . c om List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) { if (item.isFormField()) { String name = item.getName(); String value = ""; if (name.compareTo("textBoxFormElement") == 0) { value = item.getString(); } else { value = item.getString(); } response.getWriter().write(name + "=" + value + "\n"); } else { byte[] fileContents = item.get(); String message = new String(fileContents); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(message); System.out.println("UploadFunction - file uploaded"); } } else { System.out.println("UploadFunction - file rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadFunction - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . j av a 2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException 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("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } //Init Jpa CategoryJpaController categoryJpa = new CategoryJpaController(emf); StyleJpaController styleJpa = new StyleJpaController(emf); ProjectJpaController projectJpa = new ProjectJpaController(emf); IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf); // get Object Category by categoryId int cateId = Integer.parseInt((String) params.get("ddlCategory")); Category cate = categoryJpa.findCategory(cateId); // get Object Style by styleId int styleId = Integer.parseInt((String) params.get("ddlStyle")); Style style = styleJpa.findStyle(styleId); // get Object Project by projectId int projectId = Integer.parseInt((String) params.get("txtProjectId")); Project project = projectJpa.findProject(projectId); project.setStatus(Constant.STATUS_WAIT); projectJpa.edit(project); //Get param String title = (String) params.get("title"); String description = (String) params.get("description"); String url = "images/" + fileName; //Init IdeabookPhoto IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project); photoJpa.create(photo); url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId; //System HDSystem system = new HDSystem(); system.setNotificationProject(request); response.sendRedirect(url); } } catch (Exception e) { log("Error at AddImageToProjectServlet: " + e.getMessage()); } finally { out.close(); } }
From source file:edu.ucla.loni.server.Upload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {/*from w w w . ja v a 2s. com*/ @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); // Go through the items and get the root and package String rootPath = ""; String packageName = ""; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("root")) { rootPath = item.getString(); } else if (item.getFieldName().equals("packageName")) { packageName = item.getString(); } } } if (rootPath.equals("")) { res.getWriter().println("error :: Root directory has not been found."); return; } Directory root = Database.selectDirectory(rootPath); // Go through items and process urls and files for (FileItem item : items) { // Uploaded File if (item.isFormField() == false) { String filename = item.getName(); ; if (filename.equals("") == true) continue; try { InputStream in = item.getInputStream(); //determine if it is pipefile or zipfile //if it is pipefile => feed directly to writeFile function //otherwise, uncompresse it first and then one-by-one feed to writeFile if (filename.endsWith(".zip")) { ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); while (entry != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (baos != null) { byte[] arr = new byte[4096]; int index = 0; while ((index = zip.read(arr, 0, 4096)) != -1) { baos.write(arr, 0, index); } } InputStream is = new ByteArrayInputStream(baos.toByteArray()); writeFile(root, packageName, is); entry = zip.getNextEntry(); } zip.close(); } else { writeFile(root, packageName, in); } in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage()); } } // URLs if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false) { String urlListAsStr = item.getString(); String[] urlList = urlListAsStr.split("\n"); for (String urlStr : urlList) { try { URL url = new URL(urlStr); URLConnection urlc = url.openConnection(); InputStream in = urlc.getInputStream(); writeFile(root, packageName, in); in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + urlStr); return; } } } } } catch (Exception e) { res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage()); } } }
From source file:com.controller.RecipeImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w .ja 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, IOException { response.setContentType("text/html;charset=UTF-8"); //retrieving the path to store image from web.xml filePath = getServletContext().getInitParameter("recipeImageStorePath"); //retrieving the path to display image from web.xml fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath"); // 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; } 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>"); out.println("1"); while (i.hasNext()) { out.println("2"); FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); fileName = randomString(fileName); 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.println("Uploaded Filename: " + fileName + "<br>" + filePath); } else { out.println("No file"); } } out.println("</body>"); out.println("</html>"); RecipeBean recipeBean = new RecipeBean(); RecipeDAO recipeDAO = new RecipeDAO(); String image = fileDisplay + "" + fileName; out.println(image); HttpSession session = request.getSession(); String recipeId = (String) session.getAttribute("recipeId"); session.removeAttribute("recipeId"); recipeDAO.addImage(recipeId, image); response.sendRedirect("Home"); } catch (Exception ex) { System.out.println(ex); } }
From source file:admin.controller.ServletUploadFonts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w.j a va2s. 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 */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); String filePath; String file_name = null, field_name, upload_path; RequestDispatcher request_dispatcher; String font_name = "", look_id; String font_family_name = ""; PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { // 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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("fontname")) { font_name = fi.getString(); } if (field_name.equals("fontstylecss")) { font_family_name = fi.getString(); } } else { // check = fonts.checkAvailability(font_name); // if (check == false){ field_name = fi.getFieldName(); file_name = fi.getName(); if (file_name != "") { File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH); if (!uploadDir.exists()) { uploadDir.mkdirs(); } boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } fonts.addFont(font_name, file_name, font_family_name); response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp"); // }else { // response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist"); // } } } } } catch (Exception e) { logger.log(Level.SEVERE, "Exception while uploading fonts", e); } }
From source file:com.skin.generator.action.UploadTestAction.java
/** * @param request// w ww . ja v a 2 s . c om * @return Map<String, Object> * @throws Exception */ public Map<String, Object> parse(HttpServletRequest request) throws Exception { String repository = System.getProperty("java.io.tmpdir"); int maxFileSize = 1024 * 1024 * 1024; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(repository)); factory.setSizeThreshold(1024 * 1024); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setFileSizeMax(maxFileSize); servletFileUpload.setSizeMax(maxFileSize); Map<String, Object> map = new HashMap<String, Object>(); List<?> list = servletFileUpload.parseRequest(request); if (list != null && list.size() > 0) { for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { logger.debug("form field: {}, {}", item.getFieldName(), item.toString()); map.put(item.getFieldName(), item.getString("utf-8")); } else { logger.debug("file field: {}", item.getFieldName()); map.put(item.getFieldName(), item); } } } return map; }
From source file:controllers.LinguagemController.java
private void adicionarOuEditarLinguagem() throws IOException, ServletException { String anoLancamento, nome, id, licenca, descricao, caminhoLogo; anoLancamento = nome = licenca = descricao = caminhoLogo = id = ""; File file;//from ww w . j a v a 2 s .c om int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = getServletContext(); String filePath = context.getInitParameter("file-upload"); String contentType = request.getContentType(); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = fi.getName(); if (fileName != null) { String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); file = new File(filePath + name); caminhoLogo = file.getName(); fi.write(file); } } else { String campo = fi.getFieldName(); String valor = fi.getString("UTF-8"); switch (campo) { case "nome": nome = valor; break; case "ano_lancamento": anoLancamento = valor; break; case "licenca": licenca = valor; break; case "descricao": descricao = valor; break; case "id": id = valor; break; default: break; } } } } catch (Exception ex) { System.out.println(ex); } } boolean atualizando = !id.isEmpty(); if (atualizando) { Linguagem linguagem = dao.select(Integer.parseInt(id)); linguagem.setAnoLancamento(anoLancamento); linguagem.setDescricao(descricao); linguagem.setLicenca(licenca); linguagem.setNome(nome); if (!caminhoLogo.isEmpty()) { File imagemAntiga = new File(filePath + linguagem.getCaminhoLogo()); imagemAntiga.delete(); linguagem.setCaminhoLogo(caminhoLogo); } dao.update(linguagem); } else { Linguagem linguagem = new Linguagem(nome, anoLancamento, licenca, descricao, caminhoLogo); dao.insert(linguagem); } response.sendRedirect("linguagens.jsp"); // response.getWriter().print("<script>setTimeout(function () {" // + "window.location.href='linguagens.jsp';" // + "}" // + ", 1500);</script>"); }