List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:forseti.JSubirArchivo.java
@SuppressWarnings("rawtypes") public int processFiles(HttpServletRequest request, boolean onlyOne) // Request No debe contener parametros de formulario, sino solo los parmetro del archivo { int numFiles = 0, thisFile = 0; try {/*w w w. ja v a 2 s . c o m*/ // construimos el objeto que es capaz de parsear la pericin DiskFileUpload fu = new DiskFileUpload(); // maximo numero de bytes fu.setSizeMax(1024 * m_MaxSize); // 512 K // tamao por encima del cual los ficheros son escritos directamente en disco fu.setSizeThreshold(4096); // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria fu.setRepositoryPath("/tmp"); // ordenamos procesar los ficheros List fileItems = fu.parseRequest(request); if (fileItems == null) { m_Error += JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " null"; return 0; } // Iteramos por cada fichero Iterator i = fileItems.iterator(); FileItem actual = null; if (onlyOne) { actual = (FileItem) i.next(); String fileName = actual.getName(); // construimos un objeto file para recuperar el trayecto completo File file = new File(fileName); // Verifica que el archivo sea de la extension esperada for (int f = 0; f < m_Files.size(); f++) { String ext = "." + getExt(f).toLowerCase(); System.out.println("Archivo: " + fileName + " Ext esperada: " + ext); if (file.getName().toLowerCase().indexOf(ext) != -1) { // nos quedamos solo con el nombre y descartamos el path file = new File(m_Path + file.getName()); // escribimos el fichero colgando del nuevo path actual.write(file); MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile); part.m_File = file.getName(); numFiles += 1; break; } } if (numFiles == 0) m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName(); } else { while ((actual = (FileItem) i.next()) != null) { String fileName = actual.getName(); // construimos un objeto file para recuperar el trayecto completo File file = new File(fileName); String ext = "." + getExt(thisFile).toLowerCase(); System.out.println("Archivo: " + fileName + " Ext esperada: " + ext); // Verifica que el archivo sea de la extension esperada if (file.getName().toLowerCase().indexOf(ext) != -1) { // nos quedamos solo con el nombre y descartamos el path file = new File(m_Path + file.getName()); // escribimos el fichero colgando del nuevo path actual.write(file); MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile); part.m_File = file.getName(); numFiles += 1; } else m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - " + ext; thisFile += 1; } System.out.println("Despues while"); } } catch (Exception e) { if (e != null) m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage(); } return numFiles; }
From source file:com.krawler.esp.handlers.genericFileUpload.java
public void doPost(List fileItems, String filename, String destinationDirectory) { File destDir = new File(destinationDirectory); Ext = "";/* w ww. j av a 2s . c om*/ if (!destDir.exists()) { destDir.mkdirs(); } DiskFileUpload fu = new DiskFileUpload(); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) Ext = fileName.substring(fileName.lastIndexOf(".")); if (fi.getSize() != 0) { this.isUploaded = true; File uploadFile = new File(destinationDirectory + "/" + filename + Ext); fi.write(uploadFile); imgResize(destinationDirectory + "/" + filename + Ext, 100, 100, destinationDirectory + "/" + filename + "_100"); imgResize(destinationDirectory + "/" + filename + Ext, 35, 35, destinationDirectory + "/" + filename); } else { this.isUploaded = false; } } catch (Exception e) { logger.warn(e.getMessage(), e); } } } }
From source file:com.origami.sgm.services.ejbs.censocat.FotosServlet.java
protected void postWithNumId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FotoUploadRespMod respModel = new FotoUploadRespMod(false, null); try {// w w w .j a v a2 s. c o m response.setContentType("application/json;charset=UTF-8"); this.genFactory(); Long id = Long.parseLong(request.getParameter("id")); uploadFotoBean.setPredioId(id); boolean isMultipart = ServletFileUpload.isMultipartContent(request); ServletFileUpload upload = new ServletFileUpload(uploadFotoBean.getFactory()); upload.setFileSizeMax(10000000); // max 10MB List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { } else { InputStream is = item.getInputStream(); Long fileId = omegaUploader.uploadFile(is, item.getName(), item.getContentType()); uploadFotoBean.setFileId(fileId); uploadFotoBean.setNombre(item.getName()); uploadFotoBean.setContentType(item.getContentType()); uploadFotoBean.saveFotoId(); respModel.setFotoId(uploadFotoBean.getFotoPredioId()); respModel.setOk(true); is.close(); break; } } } catch (FileUploadException ex) { Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (NumberFormatException | IOException ex) { Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex); } ObjectMapper mapper = new ObjectMapper(); String jsonResp = mapper.writeValueAsString(respModel); response.getWriter().write(jsonResp); }
From source file:com.silverpeas.form.AbstractFormTest.java
@Test public void testIsEmptyWithNoFileItemsFound() 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 fileItem = mock(FileItem.class); when(fileItem.getFieldName()).thenReturn(""); when(fileItem.getName()).thenReturn(""); when(fileItem.isFormField()).thenReturn(true); boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem, fileItem), dataRecord, pagesContext); assertTrue(isEmpty);/*w ww . j a v a 2 s . c o m*/ }
From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java
/** * Save files to baseDirectoryForFiles and return a list of File objects. * @param fileStreams/*www . ja v a 2 s. c o m*/ * @return * @throws ServletException */ private List<File> saveFiles(Map<String, List<FileItem>> fileStreams) throws ServletException { // save files to disk List<File> filesToLoad = new ArrayList<File>(); for (String fileItemKey : fileStreams.keySet()) { for (FileItem fileItem : fileStreams.get(fileItemKey)) { String originalName = fileItem.getName(); String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_"); name = name.replace("..", "_"); name = name.trim().toLowerCase(); String saveLocation = baseDirectoryForFiles + File.separator + name; String savedName = name; int next = 0; boolean foundUnusedName = false; while (!foundUnusedName) { File test = new File(saveLocation); if (test.exists()) { next++; savedName = name + '(' + next + ')'; saveLocation = baseDirectoryForFiles + File.separator + savedName; } else { foundUnusedName = true; } } File uploadedFile = new File(saveLocation); try { fileItem.write(uploadedFile); } catch (Exception ex) { log.error("Unable to save POSTed file. " + ex.getMessage()); throw new ServletException("Unable to save file to the disk. " + ex.getMessage()); } if (fileItem.getSize() < 1) { throw new ServletException("No file was uploaded or file was empty."); } else { filesToLoad.add(uploadedFile); } } } return filesToLoad; }
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /*from www .jav a2s . c o m*/ * 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. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); 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 + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new 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); if (extIsAllowed(typeStr, ext)) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS"); newName = format.format(new Date()) + String.valueOf(((int) (Math.random() * 100000))) + "." + ext; fileUrl = currentPath + "/" + newName; pathToSave = new File(currentDirPath, newName); uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } 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(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.krawler.esp.handlers.genericFileUpload.java
public void doPostCompay(List fileItems, String filename, String destinationDirectory) { File destDir = new File(destinationDirectory); Ext = "";// ww w .j a v a 2 s. co m if (!destDir.exists()) { destDir.mkdirs(); } DiskFileUpload fu = new DiskFileUpload(); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) Ext = fileName.substring(fileName.lastIndexOf(".")); if (fi.getSize() != 0) { this.isUploaded = true; File uploadFile = new File(destinationDirectory + "/" + "temp_" + filename + Ext); fi.write(uploadFile); imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 0, 0, destinationDirectory + "/original_" + filename, true); imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 130, 25, destinationDirectory + "/" + filename, false); // imgResize(destinationDirectory + "/" + filename + Ext, // 0, 0, destinationDirectory + "/original_" + filename); uploadFile.delete(); } else { this.isUploaded = false; } } catch (Exception e) { this.ErrorMsg = "Problem occured while uploading logo"; logger.warn(e.getMessage(), e); } } } }
From source file:com.nemesis.admin.UploadServlet.java
/** * @param request/*from w ww .ja v a 2s .c o m*/ * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) * */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JsonArray json = new JsonArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName()); File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile); item.write(file); JsonObject jsono = new JsonObject(); jsono.addProperty("name", savedFile); jsono.addProperty("path", file.getAbsolutePath()); jsono.addProperty("size", item.getSize()); json.add(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:com.pdfhow.diff.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request// ww w. j a v a 2 s .c om * servlet request * @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 { if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JSONArray json = new JSONArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName()); item.write(file); JSONObject jsono = new JSONObject(); jsono.put("name", item.getName()); jsono.put("size", item.getSize()); jsono.put("url", "UploadServlet?getfile=" + item.getName()); jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName()); jsono.put("delete_url", "UploadServlet?delfile=" + item.getName()); jsono.put("delete_type", "GET"); json.put(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:com.intranet.intr.contabilidad.EmpControllerGastos.java
@RequestMapping(value = "EupdateGastoRF.htm", method = RequestMethod.POST) public String EupdateGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {/*from w w w.j ava2 s.c om*/ String mensaje = ""; String ruta = "redirect:EGastos.htm"; //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (gr.getIdgasto() != 0) { if (gastosRService.existe(item.getName()) == false) { System.out.println("updateeeNOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.updateGasto(gr); } } else ruta = "redirect:EGastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }