List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.silverpeas.form.AbstractFormTest.java
@Test public void testIsEmptyWithAllFileItemsWithoutContent() throws Exception { MyFormImpl myForm = new MyFormImpl( new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1), new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2))); DataRecord dataRecord = mock(DataRecord.class); PagesContext pagesContext = mock(PagesContext.class); FileItem fileItem1 = mock(FileItem.class); when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1); when(fileItem1.getName()).thenReturn(FIELD_NAME1); when(fileItem1.isFormField()).thenReturn(true); when(fileItem1.getString(anyString())).thenReturn(""); FileItem fileItem2 = mock(FileItem.class); when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2); when(fileItem2.getName()).thenReturn(FIELD_NAME2); when(fileItem2.isFormField()).thenReturn(true); when(fileItem2.getString(anyString())).thenReturn(null); boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext); assertTrue(isEmpty);// ww w.j a v a 2 s. c o m }
From source file:com.silverpeas.form.AbstractFormTest.java
@Test public void testIsNotEmptyWithOnlyOneFileItemWithoutContent() throws Exception { MyFormImpl myForm = new MyFormImpl( new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1), new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2))); DataRecord dataRecord = mock(DataRecord.class); PagesContext pagesContext = mock(PagesContext.class); FileItem fileItem1 = mock(FileItem.class); when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1); when(fileItem1.getName()).thenReturn(FIELD_NAME1); when(fileItem1.isFormField()).thenReturn(true); when(fileItem1.getString(anyString())).thenReturn("tartempion"); FileItem fileItem2 = mock(FileItem.class); when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2); when(fileItem2.getName()).thenReturn(FIELD_NAME2); when(fileItem2.isFormField()).thenReturn(true); when(fileItem2.getString(anyString())).thenReturn(null); boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext); assertFalse(isEmpty);// w ww . ja va 2 s . c o m }
From source file:br.com.caelum.vraptor.interceptor.multipart.MultipartItemsProcessor.java
public void process() { Multimap<String, String> params = LinkedListMultimap.create(); for (FileItem item : items) { if (item.isFormField()) { params.put(item.getFieldName(), getValue(item)); continue; }/*ww w .java 2 s .c o m*/ if (notEmpty(item)) { try { UploadedFile fileInformation = new DefaultUploadedFile(item.getInputStream(), item.getName(), item.getContentType()); parameters.setParameter(item.getFieldName(), item.getName()); request.setAttribute(item.getName(), fileInformation); logger.debug("Uploaded file: {} with {}", item.getFieldName(), fileInformation); } catch (Exception e) { throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e); } } else { logger.debug("A file field was empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); parameters.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } }
From source file:com.intranet.intr.proyecto.EmpControllerProyectoGaleriaCertificaciones.java
@RequestMapping(value = "EProyectoGaleria.htm", method = RequestMethod.POST) public String ProyectoGaleria_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer, BindingResult result, HttpServletRequest request) { String mensaje = ""; //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\ String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosCertificaciones"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024);/*w ww . j a v a2 s .c o m*/ ServletFileUpload upload = new ServletFileUpload(factory); String ruta = "redirect:EProyectoGaleria.htm?nifC=" + nifC + "&id=" + idP; try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (idP != 0) { galer.setIdPropuesta(idP); if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) { File file = new File(ubicacionArchivo, item.getName()); item.write(file); galer.setNombreimg(item.getName()); proyectoCertificacionesGaleriaService.insertar2(galer); } } else ruta = "redirect:ELtaClientesProyecto.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } //return "redirect:uploadFile.htm"; return ruta; }
From source file:com.kodemore.servlet.control.ScDropzone.java
private void tryHandleUpload() { try {/* w ww . j a v a 2 s . c om*/ KmList<FileItem> files = getData().getUploadedFiles(); for (FileItem item : files) try (BufferedInputStream in = Kmu.toBufferedInputStream(item.getInputStream())) { String fileName = FilenameUtils.getName(item.getName()); byte[] data = Kmu.readBytesFrom(in); getUploadHandler().upload(fileName, data); } } catch (IOException ex) { KmLog.error(ex, "Dropzone upload failure."); } }
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {/* w ww . j a va 2 s . co m*/ items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:com.truthbean.core.web.kindeditor.FileUpload.java
@Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final PageContext pageContext; HttpSession session = null;/*from w w w . j a v a 2s .c o m*/ final ServletContext application; final ServletConfig config; JspWriter out = null; final Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); /** * KindEditor JSP * * JSP???? ?? * */ // ? String savePath = pageContext.getServletContext().getRealPath("/") + "resource/"; String savePath$ = savePath; // ?URL String saveUrl = request.getContextPath() + "/resource/"; // ??? HashMap<String, String> extMap = new HashMap<>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); // ? long maxSize = 10 * 1024 * 1024 * 1024L; response.setContentType("text/html; charset=UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { out.println(getError("")); return; } // File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { out.println(getError("?")); return; } // ?? if (!uploadDir.canWrite()) { out.println(getError("??")); return; } String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; } if (!extMap.containsKey(dirName)) { out.println(getError("???")); return; } // savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); if (!item.isFormField()) { // ? if (item.getSize() > maxSize) { out.println(getError("??")); return; } // ?? String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) { out.println(getError("??????\n??" + extMap.get(dirName) + "?")); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try { File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); } catch (Exception e) { out.println(getError("")); return; } JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); request.getSession().setAttribute("fileName", savePath$ + fileName); request.getSession().setAttribute("filePath", savePath + newFileName); request.getSession().setAttribute("fileUrl", saveUrl + newFileName); out.println(obj.toJSONString()); } } out.write('\r'); out.write('\n'); } catch (IOException | FileUploadException t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } if (_jspx_page_context != null) { _jspx_page_context.handlePageException(t); } else { throw new ServletException(t); } } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
From source file:Controller.ControllerImageCustomer.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w w w. j av a 2 s .c o 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 { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception 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()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path" + fileName); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; System.out.println("Rpath" + RealPath); File savedFile = new File(RealPath); item.write(savedFile); String username = (String) params.get("txtusername"); String password = (String) params.get("txpassword"); String hoten = (String) params.get("txthoten"); String gioitinh = (String) params.get("txtgioitinh"); String email = (String) params.get("txtemail"); String role = "false"; String Register = (String) params.get("Register"); String url = "CustomerDao.jsp"; if (Register.equals("Register")) { url = "index.jsp"; } Customer cus = new Customer(username, password, hoten, gioitinh, email, role, "upload\\" + fileName); CustomerDAO.ThemKhachHang(cus); RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.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 w w . j a v a2 s.c o m * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); FormUserOperation formUser = Constant.getFormUserOperation(request); String fck_task_id = (String) request.getSession().getAttribute("fck_task_id"); if (fck_task_id == null) { fck_task_id = "temp_task_id"; } 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 + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); File currentDir = new File(currentDirPath); if (!currentDir.exists()) { currentDir.mkdirs(); } String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.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); //???IP String server_ip = (String) session.getAttribute("server_ip"); if (server_ip == null) { server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP? } String url = "http://" + server_ip + currentPath.substring(2, currentPath.length()); fileUrl = url + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = url + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; } } 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"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:com.intranet.intr.proyecto.SupControllerProyectoGaleriaCertificaciones.java
@RequestMapping(value = "ProyectoGaleria.htm", method = RequestMethod.POST) public String ProyectoGaleria_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer, BindingResult result, HttpServletRequest request) { String mensaje = ""; //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\ String ubicacionArchivo = "E:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024);//from ww w .j a v a 2 s . c o m ServletFileUpload upload = new ServletFileUpload(factory); String ruta = "redirect:ProyectoGaleria.htm?nifC=" + nifC + "&id=" + idP; try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (idP != 0) { galer.setIdPropuesta(idP); if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) { File file = new File(ubicacionArchivo, item.getName()); item.write(file); galer.setNombreimg(item.getName()); proyectoCertificacionesGaleriaService.insertar2(galer); } } else ruta = "redirect:SLtaClientesProyecto.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } //return "redirect:uploadFile.htm"; return ruta; }