List of usage examples for org.apache.commons.fileupload FileItem isInMemory
boolean isInMemory();
From source file:servlets.UploadServlet2.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // 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;/*from ww w . ja v a2s. 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(filePath)); // 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)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); response.sendRedirect("admin.jsp"); } catch (Exception ex) { System.out.println(ex); } }
From source file:servletServices.serviceFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j av a 2 s. 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 { HttpSession session = request.getSession(); int pkStudent = 0; if (session.getAttribute("pkStudent") != null) { pkStudent = Integer.parseInt(session.getAttribute("pkStudent").toString()); } if (request.getParameter("update") != null) { String field_name = request.getParameter("update"); String field_value; try (PrintWriter out = response.getWriter()) { if (session.getAttribute("pkStudent") != null) { File file; int maxFileSize = 5000 * 1024 * 50; int maxMemSize = 5000 * 1024 * 50; // Verify the content type String contentType = request.getContentType(); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. // Path String enrollment = session.getAttribute("enrollmentStudent").toString(); String path = "C:/temp/" + enrollment; File filePath = new File(path); if (filePath.exists()) { factory.setRepository(filePath); } else { filePath.mkdirs(); factory.setRepository(filePath); } // 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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (sizeInBytes <= 1048576) { field_value = field_name.replace("fl_", ""); if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + "/" + field_value + ".pdf"); } else { file = new File(filePath + "/" + field_value + ".pdf"); //file = new File( filePath +"/"+ fileName.substring(fileName.lastIndexOf("\\")+1)); } fi.write(file); //out.println("Archivo cargado en " +filePath +""); //Establecer los parametros a la BD if (new studentControl() .UpdateStudent(pkStudent, field_name, (path + "/" + field_value + ".pdf")) .equals("Datos Modificados")) { out.print("Cargado"); } else { out.print("Fail"); } } else { out.print("File much long"); } } } } catch (Exception ex) { out.println(ex); } } else { out.println("<p>No existe un archivo en este campo</p>"); } } else { response.sendRedirect("siut/alumnos.jsp"); } } } if (request.getParameter("viewFile") != null) { try (ServletOutputStream out = response.getOutputStream()) { String fileType = request.getParameter("viewFile"); String enrollment = session.getAttribute("enrollmentStudent").toString(); if (enrollment != null) { String pdfPath = "C://temp/" + enrollment + "/" + fileType + ".pdf"; File existFile = new File(pdfPath); if (existFile.exists()) { ServletOutputStream outs = response.getOutputStream(); response.setContentType("application/pdf"); File file = new File(pdfPath); response.setHeader("Content-disposition", "inline; filename=" + enrollment + "-" + fileType + ".pdf"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { InputStream isr = new FileInputStream(file); bis = new BufferedInputStream(isr); bos = new BufferedOutputStream(outs); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { response.setContentType("text/html;charset=UTF-8"); out.println("Exception ----- Message ---" + e); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } else { response.setContentType("text/html;charset=UTF-8"); out.print("Lo sentimos no se encuentra el archivo :("); } } else { response.sendRedirect("siut/alumnos.jsp"); } } } //Load files of databases binary /*if(request.getParameter("viewFile")!=null){ try(ServletOutputStream out = response.getOutputStream()){ String file=request.getParameter("viewFile"); byte[] pdfFile; pdfFile =new studentControl().SelectFile(file, pkStudent); if((pdfFile.length>0)){ response.setContentType("application/pdf"); out.write(pdfFile); }else{ out.print("<h1>No Hay Archivo en la Base de Datos</h1>"); } if(Arrays.toString(pdfFile).equals("null")){ out.print("<h1>Parametros incorrectos!</h1>"); } } }*/ }
From source file:util.Upload.java
public boolean formProcess(ServletContext sc, HttpServletRequest request) { this.form = new HashMap<String, String>(); Map<String, String> itemForm; File file;/*from ww w . j a va2 s.c o m*/ int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = sc.getRealPath("//" + this.folderUpload); boolean ret; String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 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 fieldName = fi.getFieldName(); String fileName = fi.getName(); if (!fileName.isEmpty()) { boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String name = new Date().getTime() + fileName; file = new File(filePath + "/" + name); fi.write(file); files.add(name); } } else { form.put(fi.getFieldName(), fi.getString()); } } ret = true; } catch (Exception ex) { System.out.println(ex); ret = false; } } else { ret = false; } return ret; }
From source file:utn.frc.dlc.goses.CtrlUpload.UploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // 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;/*from w w w.j ava 2 s . c o 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("file/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)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); File afile = new File(filePath + fileName); Indexacion index = new Indexacion(file.getAbsolutePath()); if (afile.renameTo(new File("file/share/" + afile.getName()))) { out.println(fileName + " is upload successful!" + "<br>"); } else { out.println(fileName + " is failed to upload!" + "<br>"); } } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:voucherShop.ControllerVoucher.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w.java 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"); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; //ServletContext context = pageContext.getServletContext(); String filePath = getServletContext().getInitParameter("file-upload"); 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("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); out.println("1"); try { out.println("2"); // 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()) { out.println("3"); FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { out.println("4"); // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); out.println(fileName); // 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)); } out.println(filePath); try { fi.write(file); } catch (Exception ex) { System.out.println("li ....."); System.out.println(ex); } out.println("4"); out.println("Uploaded Filename: " + filePath + fileName + "<br>"); } else { out.println("sai ding dan"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } } else { 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>"); } }
From source file:works.cirno.mocha.InvokeTarget.java
public void invoke(String uri, InvokeContext context) { long beginTime = 0; if (perfLog.isDebugEnabled()) { perfLog.debug("Invoking {}", uri); beginTime = System.nanoTime(); }//w ww . jav a 2 s .c om try { HttpServletRequest req = context.getRequest(); HttpServletResponse resp = context.getResponse(); if (ServletFileUpload.isMultipartContent(req)) { try { // TODO Rework this to make it configurable and reuseable FileItemFactory fileItemFactory = new DiskFileItemFactory( DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, uploadTemp); context.setMultipart(true); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(req); for (FileItem item : items) { MultiPartItem part = new MultiPartItemCommon(item); if (!item.isInMemory()) { context.registerCloseable(part, "UploadFile: " + item.getFieldName() + " name: " + item.getName()); } context.addPart(part); } } catch (FileUploadException e) { throw new RuntimeException(e); } if (perfLog.isDebugEnabled()) { perfLog.debug("Parse multipart in {}ms", (System.nanoTime() - beginTime) / 1000000.0f); beginTime = System.nanoTime(); } } int parametersCount = parameters.length; Object[] invokeParams = new Object[parametersCount]; try { // bind parameter for (int i = 0; i < parametersCount; i++) { Parameter parameter = parameters[i]; Class<?> type = parameter.getType(); Object value = ParameterSource.NOT_HERE; for (ParameterSource source : parameter.getParameterSources()) { value = source.getParameterValue(context, parameter); } if (value == ParameterSource.NOT_HERE) { value = null; } if (value == null && type.isPrimitive()) { value = defaultPrimitives.get(type); } invokeParams[i] = value; } } catch (Throwable t) { log.error("Exception occurred binding parameters {}{}", req.getRequestURI(), req.getQueryString() != null ? req.getQueryString() : "", t); handleException(context, t); } if (perfLog.isDebugEnabled()) { perfLog.debug("Parameter resolve in {}ms", (System.nanoTime() - beginTime) / 1000000.0f); beginTime = System.nanoTime(); } try { Object result = method.invoke(controller, invokeParams); if (perfLog.isDebugEnabled()) { perfLog.debug("Controller execution in {}ms", (System.nanoTime() - beginTime) / 1000000.0f); beginTime = System.nanoTime(); } handleResult(context, req, resp, result); if (perfLog.isDebugEnabled()) { perfLog.debug("Result handle in {}ms", (System.nanoTime() - beginTime) / 1000000.0f); beginTime = System.nanoTime(); } } catch (Throwable t) { log.error("Exception occurred processing request {}{}", req.getRequestURI(), req.getQueryString() != null ? req.getQueryString() : "", t); handleException(context, t); } } finally { try { context.close(); } catch (Exception e) { log.warn("Failed closing context", e); } } }