List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:Index.RegisterRestaurantImagesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . ja 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("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(ubicacionArchivo)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); List<String> listImage = (List<String>) request.getSession().getAttribute("listImagen"); if (listImage == null) { listImage = new ArrayList<String>(); } for (FileItem item : partes) { webservice.Restaurante rest = (webservice.Restaurante) request.getSession() .getAttribute("registroUsuario"); File file = new File(ubicacionArchivo, rest.getNickname() + listImage.size() + ".jpg"); item.write(file); System.out.println("name: " + item.getName()); listImage.add(rest.getNickname() + listImage.size() + ".jpg"); } request.getSession().setAttribute("listImagen", listImage); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } catch (FileUploadException ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } catch (Exception ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } } }
From source file:controller.uploadPergunta6.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w.java2 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 { String idLocal = (String) request.getParameter("idLocal"); String expressao = (String) request.getParameter("expressao"); System.out.println(expressao); String name = ""; //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); // item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); item.write(new File(AbsolutePath + File.separator + name)); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } expressao = expressao.replace("+", "%2B"); RequestDispatcher view = getServletContext().getRequestDispatcher( "/novoLocalPergunta6?id=" + idLocal + "&nomeArquivo=" + name + "&expressao=" + expressao); view.forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response); }
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 {//www . j a v a 2 s .c o 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:de.betterform.agent.web.servlet.UploadServlet.java
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String payload = ""; try {//from w ww. j a va 2s. co m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List /* FileItem */ items = upload.parseRequest(request); Iterator iter = items.iterator(); FileItem uploadItem = null; String collectionPath = ""; String collectionName = ""; String relativeUploadPath = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); if (item.isFormField() && "bfUploadPath".equals(fieldName)) { relativeUploadPath = this.getFieldValue(item); } else if (item.isFormField() && "bfCollectionPath".equals(fieldName)) { collectionPath = this.getFieldValue(item); } else if (item.isFormField() && "bfCollectionName".equals(fieldName)) { collectionName = this.getFieldValue(item); } else if (item.getName() != null) { // FileItem of the uploaded file uploadItem = item; } } if (uploadItem != null && !"".equals(relativeUploadPath)) { this.uploadFile(request, uploadItem, relativeUploadPath); } else if (!"".equals(collectionName) && !"".equals(collectionPath)) { this.createColection(request, collectionName, collectionPath); } else { LOGGER.warn("error uploading file to '" + relativeUploadPath + "'"); } } catch (FileUploadException e) { e.printStackTrace(); payload = e.getMessage(); } catch (Exception e) { e.printStackTrace(); payload = e.getMessage(); } response.getOutputStream().println("<html><body><textarea>" + payload + "</textarea></body></html>"); }
From source file:com.tryAndFitV1.servlet.image.DoUploadImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww .j av a 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 { response.setContentType("text/html;charset=UTF-8"); //process only if its multipart content String path = new File(".").getCanonicalPath(); if (ServletFileUpload.isMultipartContent(request)) { try { File file = new File(""); List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); System.out.println("filrpath1: " + name); file = new File(UPLOAD_DIRECTORY + File.separator + name); item.write(file); System.out.println("filrpath: " + UPLOAD_DIRECTORY + File.separator + name); } } //File uploaded successfully request.setAttribute("message1", "Fichier tlcharg avec succs"); String msg = file.getAbsolutePath(); System.err.println("fichier tlcharg : " + msg); request.setAttribute("message2", file.getAbsolutePath()); } catch (Exception ex) { request.setAttribute("message", "Echec " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } //request.getRequestDispatcher("/formBuilder.jsp").forward(request, response); }
From source file:edu.isi.webserver.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request) { // Download the file to the upload file folder File destinationDir = new File(DESTINATION_DIR_PATH); logger.info("File upload destination directory: " + destinationDir.getAbsolutePath()); if (!destinationDir.isDirectory()) { destinationDir.mkdir();// w ww. j a v a 2s . c o m } DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB //Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null; try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { System.out.println(item.getFieldName()); System.out.println(item.getString()); // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. System.out.println("File field name: " + item.getFieldName()); uploadedFile = new File(destinationDir, item.getName()); item.write(uploadedFile); System.out.println("File written to: " + uploadedFile.getAbsolutePath()); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }
From source file:com.app.uploads.ImageUploads.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . j av 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"); PrintWriter out = response.getWriter(); String[] Fielname = new String[2]; CallableStatement pro; int i = 0; String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\"); try { if (ServletFileUpload.isMultipartContent(request)) { try { String name = ""; List<FileItem> multiparts; multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); } else if (item.isFormField()) { String fiel = item.getFieldName(); InputStream is = item.getInputStream(); byte[] b = new byte[is.available()]; is.read(b); if (i == 0) { Fielname[0] = new String(b); } else { Fielname[1] = new String(b); } i++; } } //File uploaded successfully Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName, Dir.PassWord); pro = connect.prepareCall("{call STILL_INSERT(?,?,?)}"); pro.setString(1, name); pro.setString(2, Fielname[0]); pro.setString(3, Fielname[1]); pro.executeQuery(); pro.close(); connect.close(); request.setAttribute("message", "File Uploaded Successfully"); request.setAttribute("name", name); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } out.print("Description:" + Fielname[0]); out.print("Locator:" + Fielname[1]); String pathReal = getServletContext().getRealPath("\\uploads\\"); request.setAttribute("Description", Fielname[0]); request.setAttribute("Locator", Fielname[1]); request.setAttribute("path", pathReal); request.getRequestDispatcher("/result.jsp").forward(request, response); } finally { out.close(); } }
From source file:Index.RegisterClienteImagesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w. j a v 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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String ubicacionArchivo = "~\\NetBeansProjects\\QuickOrderWeb\\web\\images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(ubicacionArchivo)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); webservice.Cliente client = new webservice.Cliente(); for (FileItem item : partes) { client = (webservice.Cliente) request.getSession().getAttribute("registroUsuario"); File file = new File(ubicacionArchivo, client.getNickname() + ".jpg"); item.write(file); System.out.println("name: " + item.getName()); client.setImagen(client.getNickname() + ".jpg"); } QuickOrderWebService webService = new QuickOrderWebService(); ControllerInterface port = webService.getQuickOrderWebServicePort(); port.registrarCliente(client); request.setAttribute("error", null); request.setAttribute("agregado", "OK"); request.removeAttribute("registroUsuario"); request.getSession().removeAttribute("userName"); request.getRequestDispatcher("/AltaCliente.jsp").forward(request, response); } catch (FileUploadException ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.setAttribute("error", "Error al subir la imagen"); request.setAttribute("funcionalidad", "Imagen"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } catch (Exception ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.setAttribute("error", "Error al subir la imagen"); request.setAttribute("funcionalidad", "Imagen"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } } }
From source file:AES.Controllers.FileController.java
@RequestMapping(value = "/upload", method = RequestMethod.GET) public void upload(HttpServletResponse response, HttpServletRequest request, @RequestParam Map<String, String> requestParams) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Hello<br/>"); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("You are not trying to upload<br/>"); return;//from w w w. j ava 2s .c o m } out.println("You are trying to upload<br/>"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { out.println("No fields found"); return; } out.println("<table border=\"1\">"); while (it.hasNext()) { out.println("<tr>"); FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString()); out.println("</td>"); } else { out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName() + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): " + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString()); out.println("</td>"); String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\"; //System.out.println(request.getSession().getServletContext().getRealPath("")); File f = new File(path + fileItem.getName()); if (!f.exists()) f.createNewFile(); fileItem.write(f); } out.println("</tr>"); } out.println("</table>"); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception ex) { Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.commerce.zocalo.JspSupport.ExperimenterScreen.java
public void processRequest(HttpServletRequest request, HttpServletResponse response) { Session session = SessionSingleton.getSession(); try {/*w w w . j av a 2 s. co m*/ if (null == action) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); for (Iterator iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = (FileItem) iterator.next(); if (fileItem.getFieldName().equals(FILENAME_FIELD)) { SessionSingleton.setSession(processStream(fileItem.getInputStream())); } } } } else if (session == null) { return; } else if (session.startRoundActionLabel().equalsIgnoreCase(action)) { session.startNextTimedRound(); } else if (DISPLAY_SCORES_ACTION.equals(action)) { if (session instanceof JudgingSession) { JudgingSession jSession = (JudgingSession) session; jSession.endScoringPhase(); message = ""; } else { message = "judging not enabled."; } } else if (STOP_VOTING_ACTION.equals(action)) { if (session instanceof VotingSession) { VotingSession vSession = (VotingSession) session; vSession.endVoting(); message = ""; } else { message = "judging not enabled."; } } else if (action != null && action.startsWith(session.stopRoundActionLabel())) { session.endTrading(true); } } catch (ScoreException e) { message = "unable to calculate scores. Have the judges entered estimates?"; } catch (IOException e) { return; } catch (Exception e) { return; } if (request != null && "POST".equals(request.getMethod())) { redirectResult(request, response); } }