List of usage examples for org.apache.commons.fileupload FileUploadException printStackTrace
public void printStackTrace()
From source file:hd.controller.AddImageToIdeaBookServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .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 { 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(); } } } String ideaBookIdTemp = (String) params.get("txtIdeabookId"); int ideaBookId = Integer.parseInt(ideaBookIdTemp); IdeaBookDAO ideabookDao = new IdeaBookDAO(); String tilte = (String) params.get("newGalleryName"); String description = (String) params.get("GalleryDescription"); String url = "images/" + fileName; IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO(); IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId); HDSystem system = new HDSystem(); system.setNotificationIdeaBook(request); response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:com.aptechfpt.controller.InsertSalePerson.java
protected void Register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w .j a v a 2 s . c o m*/ boolean isMultipartContext = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fields = upload.parseRequest(request); AccountDTO.Builder builder = new AccountDTO.Builder(); for (Iterator<FileItem> it = fields.iterator(); it.hasNext();) { FileItem fileItem = it.next(); switch (fileItem.getFieldName()) { case "email": System.out.println("email: " + fileItem.getString()); builder.Email(fileItem.getString()); continue; case "password": System.out.println("password: " + fileItem.getString()); builder.Password(fileItem.getString()); continue; case "image": System.out.println("image: " + fileItem.getName()); builder.ImageLink(writeFile(fileItem)); continue; case "firstName": System.out.println("firstName: " + fileItem.getString()); builder.FirstName(fileItem.getString()); continue; case "lastName": System.out.println("lastName: " + fileItem.getString()); builder.LastName(fileItem.getString()); continue; case "phone": System.out.println("phone: " + fileItem.getString()); builder.Phone(fileItem.getString()); continue; case "address": System.out.println("address: " + fileItem.getString()); builder.Address(fileItem.getString()); continue; case "gender": System.out.println("gender: " + fileItem.getString()); builder.Gender(AccountGender.valueOf(fileItem.getString())); continue; // case "role": // System.out.println("role: " + fileItem.getString()); // builder.Role(Role.valueOf(fileItem.getString())); case "dateOfBirth": System.out.println("dateOfBirth: " + fileItem.getString()); builder.DateOfBirth(new DateTime(fileItem.getString())); } } builder.Role(Role.SALEPERSON); AccountDTO dto = builder.build(); System.out.println("Email: " + dto.getEmail()); System.out.println("Password: " + dto.getPassword()); System.out.println("Image Link: " + dto.getImageLink()); System.out.println("First Name: " + dto.getFirstName()); System.out.println("Last Name: " + dto.getLastName()); System.out.println("Gender: " + dto.getGender()); System.out.println("Phone: " + dto.getPhone()); System.out.println("Address: " + dto.getAddress()); System.out.println("Date Of Birth: " + dto.getDateOfBirth()); accountFacade.create(dto.toAccount()); StringBuilder jsonRes = new StringBuilder(); jsonRes.append("{\"message\":").append("\"Account ").append(dto.getEmail()) .append(" create successfull.").append("\"}"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(jsonRes.toString()); out.close(); } catch (FileUploadException ex) { ex.printStackTrace(); Logger.getLogger(InsertSalePerson.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:massbank.FileUpload.java
/** * t@CAbv??[h/*w w w . j ava2 s . c om*/ * multipart/form-datat@CAbv??[h * s??nullp * @return Abv??[ht@C?MAP<t@C, Abv??[h> */ @SuppressWarnings("unchecked") public HashMap<String, Boolean> doUpload() { if (fileItemList == null) { try { fileItemList = (List<FileItem>) parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); return null; } } upFileMap = new HashMap<String, Boolean>(); for (FileItem fItem : fileItemList) { // t@CtB?[h?? if (!fItem.isFormField()) { String key = ""; boolean val = false; // t@C?ipX????j String filePath = (fItem.getName() != null) ? fItem.getName() : ""; // t@C?imt@C?j String fileName = (new File(filePath)).getName(); int pos = fileName.lastIndexOf("\\"); fileName = fileName.substring(pos + 1); pos = fileName.lastIndexOf("/"); fileName = fileName.substring(pos + 1); // t@CAbv??[h if (!fileName.equals("")) { key = fileName; File upFile = new File(outPath + "/" + fileName); try { fItem.write(upFile); val = true; } catch (Exception e) { e.printStackTrace(); upFile.delete(); } } upFileMap.put(key, val); } } return upFileMap; }
From source file:com.ci6225.marketzone.servlet.seller.AddProductServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//from ww w . j a v a 2 s . co m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = null; String description = null; String unitPrice = null; String quantity = null; FileItem imageItem = null; // constructs the folder where uploaded file will be stored //String uploadFolder = getServletContext().getRealPath("") + "/productImages"; // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000 * 1024); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(5000 * 1024); try { // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { if (item.getFieldName().equals("productImage") && !item.getString().equals("")) { imageItem = item; } System.out.println(item.getFieldName()); } else { System.out.println(item.getFieldName() + " " + item.getString()); if (item.getFieldName().equals("name")) { name = item.getString(); } else if (item.getFieldName().equals("description")) { description = item.getString(); } else if (item.getFieldName().equals("unitPrice")) { unitPrice = item.getString(); } else if (item.getFieldName().equals("quantity")) { quantity = item.getString(); } } } } catch (FileUploadException ex) { System.out.println(ex); ex.printStackTrace(); response.sendRedirect("./addProduct"); } catch (Exception ex) { System.out.println(ex); ex.printStackTrace(); response.sendRedirect("./addProduct"); } FormValidation validation = new FormValidation(); List<String> messageList = new ArrayList<String>(); if (!validation.validateAddProduct(name, description, quantity, unitPrice, imageItem)) { messageList.addAll(validation.getErrorMessages()); request.setAttribute("errorMessage", messageList); request.setAttribute("name", name); request.setAttribute("description", description); request.setAttribute("quantity", quantity); request.setAttribute("unitPrice", unitPrice); RequestDispatcher rd = request.getRequestDispatcher("./addProduct"); rd.forward(request, response); } try { User user = (User) request.getSession().getAttribute("user"); productBean.addProduct(name, description, user.getUserId(), Integer.parseInt(quantity), Float.parseFloat(unitPrice), imageItem); messageList.add("Product Added Successfully."); request.setAttribute("successMessage", messageList); RequestDispatcher rd = request.getRequestDispatcher("./ViewProductList"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); response.sendRedirect("./addProduct"); } }
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 {//from w ww.ja v a2s. co m 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:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w . ja va2s .com*/ * * @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:Controle.Controle_foto.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); ArrayList<Object> obj = new ArrayList<Object>(); Mensagem msg = new Mensagem(); Gson gson = new Gson(); PrintWriter out = response.getWriter(); Foto foto = new Foto(); FotoDAO fotoDAO = new FotoDAO(); System.out.println("teste"); if (isMultipart) { System.out.println("teste2"); FileItemFactory factory = new DiskFileItemFactory(); System.out.println("teste3"); ServletFileUpload upload = new ServletFileUpload(factory); try {//from w w w . j a v a 2 s .c o m System.out.println("teste4"); List itens = upload.parseRequest(request); Iterator iterator = itens.iterator(); String id = ""; String legenda = ""; id = request.getParameter("id"); // // if(id.equals("null")){ // System.out.println("sem id da foto"); // }else{ // System.out.println("com id da foto"); // } System.out.println("id da foto: " + request.getParameter("id")); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String nomeArquivo = item.getName(); String extensao = ""; System.out.println(nomeArquivo); int cont = 4; for (int i = 0; i <= 3; i++) { extensao += nomeArquivo.charAt(nomeArquivo.length() - cont); cont = cont - 1; } Random rdm = new Random(); int n = rdm.nextInt(99999); nomeArquivo = id + n + extensao; System.out.println(nomeArquivo); String diretorio = getServletContext().getRealPath("/"); File destino = new File(diretorio + "/segura/img"); System.out.println(destino); //apagar arquivo antigo. foto = fotoDAO.buscarPorId(Integer.parseInt(id)); if (foto.getId() <= 0) { throw new Exception("Foto no encontrada!!!!"); } else { File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco()); System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco()); if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) { boolean bool = arquivoAntigo.delete(); System.out.println("arquivo apagado? " + bool); System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!" + arquivoAntigo.getAbsolutePath()); } foto.setEndereco("/segura/img/" + nomeArquivo); foto.setLegenda(legenda); fotoDAO.atualizar(foto); } // if (!destino.exists()) { // boolean status = destino.mkdirs(); // // } File arquivoRecebido = new File(destino + "/" + nomeArquivo); System.out.println(arquivoRecebido.getAbsolutePath()); item.write(arquivoRecebido); } else { if (!item.getFieldName().equals("legenda")) { id = item.getString(); } else { legenda = item.getString(); } System.out.println("Nome do campo !!!" + item.getFieldName()); System.out.println("Olha o valor do id !!!" + item.getString()); } } msg.setMensagem("Cadastrado com sucesso!!!!"); msg.setTipo(1); obj.add(msg); } catch (FileUploadException e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } finally { out.printf(gson.toJson(obj)); } } else { System.out.println("deu ruim no multpart"); } }
From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java
@Override public void processForm(HttpServletRequest request, String[] parts, String currentId) throws ServletException, IOException { HashMap<String, String> parametros = new HashMap<>(); boolean fileflag = false; AvisosException aex = null;/*from w w w .j a va 2 s . co m*/ if (ServletFileUpload.isMultipartContent(request)) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_SIZE); List<FileItem> items = upload.parseRequest(request); String filename = null; for (FileItem item : items) { if (!item.isFormField() && item.getSize() > 0) { filename = processUploadedFile(item, currentId); //System.out.println("poniendo: "+ item.getFieldName() + "=" +filename); parametros.put(item.getFieldName(), filename); } else { // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"))); // parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"))); // System.out.println("item:" + item.getFieldName() + "=" + item.getString()); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"),"UTF-8")); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"))); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("UTF-8"),"UTF-8")); parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"), "UTF-8")); } } } catch (FileUploadException fue) { fue.printStackTrace(); fileflag = true; aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue); } } else { for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { // try { // parametros.put(entry.getKey(), new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1"))); // } catch (UnsupportedEncodingException ue) { // //No debe llegar a este punto // assert false; // } parametros.put(entry.getKey(), request.getParameter(entry.getKey())); } } BasicDBObject anterior = (BasicDBObject) mi.getAdvice(currentId).get(parts[3]); procesaAreas(parametros, anterior); procesaImagen(parametros, anterior); MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros); if (fileflag) { throw aex; } }
From source file:net.morphbank.mbsvc3.webservices.RestfulService.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); MorphbankConfig.SYSTEM_LOGGER.info("starting post"); response.setContentType("text/xml"); System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // response.setContentType("text/html"); try {//from w w w. j a v a 2 s .co m // Process the uploaded items List<?> /* FileItem */ items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName()); // processFormField(item); } else { // processUploadedFile(item); String paramName = item.getFieldName(); String fileName = item.getName(); InputStream stream = item.getInputStream(); // Reader reader = new InputStreamReader(stream); if ("uploadFileXml".equals(paramName)) { MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName); processRequest(stream, out, fileName); MorphbankConfig.SYSTEM_LOGGER.info("Processing complete"); } else { // Process the input stream MorphbankConfig.SYSTEM_LOGGER .info("Upload field name " + item.getFieldName() + " ignored!"); } } } } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:com.tern.web.MultiPartEnabledRequest.java
public MultiPartEnabledRequest(HttpServletRequest req) { super(req);//w w w . j a v a2 s . c om this.multipart = FileUpload.isMultipartContent(req); if (multipart) { try { readHttpParams(req); } catch (FileUploadException e) { Trace.write(Trace.Error, e, "MultiPartEnabledRequest"); e.printStackTrace(); } } }