List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.example.webapp.filter.MultipartFilter.java
/** * Process multipart request item as file field. The name and FileItem * object of each file field will be added as attribute of the given * HttpServletRequest. If a FileUploadException has occurred when the file * size has exceeded the maximum file size, then the FileUploadException * will be added as attribute value instead of the FileItem object. * /*from w w w . jav a 2 s . c o m*/ * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. */ private void processFileField(FileItem fileField, HttpServletRequest request) { if (fileField.getName().length() <= 0) { // No file uploaded. request.setAttribute(fileField.getFieldName(), null); } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) { // File size exceeds maximum file size. request.setAttribute(fileField.getFieldName(), new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk // space. fileField.delete(); } else { // File uploaded with good size. request.setAttribute(fileField.getFieldName(), fileField); } }
From source file:game.com.HandleUploadGameNesServlet.java
private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception { boolean isMultipart; String filePath;/*from ww w .j a v a2 s.c o m*/ int maxFileSize = 4 * 1024 * 1024; int maxMemSize = 4 * 1024 * 1024; File file; 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("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); Map<String, List<FileItem>> postData = upload.parseParameterMap(request); String id = postData.get("id").get(0).getString(); if (StringUtils.isBlank(id)) { logger.info("id= " + id); } try { // Parse the request to get file items. List<FileItem> fileItems = postData.get("nes"); // Process the uploaded file items for (FileItem fi : fileItems) { 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 file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/nes/" + id + ".zip"); fi.write(file); responseObject.data = getNesFileUrl(id); responseObject.returnCode = 1; responseObject.returnMessage = "success"; break; } else { logger.info("isFormField " + fi.getFieldName()); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
From source file:com.rapidsist.portal.cliente.editor.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.//from w w w . ja v a 2 s .c om * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("PASO POR EL METODO doPost DEL SERVLET SimpleUploaderServlet"); 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; 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); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; } } catch (Exception ex) { 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:cpabe.controladores.UploadDecriptacaoServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<CaminhoArquivo> lista = new ArrayList<CaminhoArquivo>(); List<File> lista2 = new ArrayList<File>(); CaminhoArquivo c = new CaminhoArquivo(); if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); }/*from w ww . j a va 2 s.c om*/ // response.setContentType("text/html"); // PrintWriter out = response.getWriter(); // out.write("<html><head></head><body>"); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println("FieldName=" + fileItem.getFieldName()); System.out.println("FileName=" + fileItem.getName()); System.out.println("ContentType=" + fileItem.getContentType()); System.out.println("Size in bytes=" + fileItem.getSize()); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); //setar no objeto CaminhoArquivo os dados do arquivo anexado String caminho = file.getAbsolutePath(); String nome = fileItem.getName(); c.setNome(nome); c.setWay(caminho); System.out.println("caminho=" + caminho); System.out.println("nome=" + nome); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); lista2.add(file); // out.write("File " + fileItem.getName() + " uploaded successfully."); // out.write("<br>"); // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>"); } } catch (FileUploadException e) { // out.write("Exception in uploading file."); } catch (Exception e) { // out.write("Exception in uploading file."); } // out.write("</body></html>"); //lendo a lista dos arquivos adicionados e pegando os caminhos do arquivo e da chave c.setWay(lista2.get(0).getAbsolutePath()); c.setNome(lista2.get(0).getName()); System.out.println("arquivo=" + lista2.get(0).getAbsolutePath()); c.setChave(lista2.get(1).getAbsolutePath()); System.out.println("chave=" + lista2.get(1).getAbsolutePath()); request.setAttribute("caminho", c); request.getRequestDispatcher("/formularios/decriptar/decriptar2.jsp").forward(request, response); }
From source file:com.king.platform.net.http.integration.MultiPart.java
@Test public void postMultiPart() throws Exception { AtomicReference<List<FileItem>> partReferences = new AtomicReference<>(); AtomicReference<Exception> exceptionReference = new AtomicReference<>(); integrationServer.addServlet(new HttpServlet() { @Override// w w w . j ava 2 s . co m protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); try { List<FileItem> fileItems = servletFileUpload.parseRequest(req); partReferences.set(fileItems); } catch (FileUploadException e) { exceptionReference.set(e); } } }, "/testMultiPart"); httpClient .createPost( "http://localhost:" + port + "/testMultiPart") .idleTimeoutMillis( 0) .totalRequestTimeoutMillis( 0) .content( new MultiPartBuilder() .addPart( MultiPartBuilder .create("text1", "Message 1", StandardCharsets.ISO_8859_1) .contentType("multipart/form-data")) .addPart(MultiPartBuilder.create("binary1", new byte[] { 0x00, 0x01, 0x02 }) .contentType("application/octet-stream").charset(StandardCharsets.UTF_8) .fileName("application.bin")) .addPart(MultiPartBuilder.create("text2", "Message 2", StandardCharsets.ISO_8859_1)) .build()) .build().execute().join(); assertNull(exceptionReference.get()); List<FileItem> fileItems = partReferences.get(); FileItem fileItem = fileItems.get(1); assertEquals("application/octet-stream; charset=UTF-8", fileItem.getContentType()); assertEquals("binary1", fileItem.getFieldName()); assertEquals("application.bin", fileItem.getName()); }
From source file:Control.HandleAddFoodMenu.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j a 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 { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); Food temp = new Food(); try (PrintWriter out = response.getWriter()) { LinkedList<String> names = new LinkedList<>(); /* TODO output your page here. You may use following sample code. */ String path = getClass().getResource("/").getPath(); String[] tempS = null; if (Paths.path == null) { File file = new File(path + "test.html"); path = file.getParent(); File file1 = new File(path + "test1.html"); path = file1.getParent(); File file2 = new File(path + "test1.html"); path = file2.getParent(); Paths.path = path; } else { path = Paths.path; } path = Paths.tempPath; String name; String sepName = Tools.CurrentTime(); if (ServletFileUpload.isMultipartContent(request)) { List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Iterator iter = multiparts.iterator(); int index = 0; tempS = new String[multiparts.size() - 1]; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { name = new File(item.getName()).getName(); names.add(name); String FilePath = path + Paths.foodImagePath + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.categoryid = Integer.parseInt(tempS[index++]); temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.price = Double.parseDouble(tempS[index++]); temp.pieces = Integer.parseInt(tempS[index++]); temp.description = tempS[index++]; temp.restid = Integer.parseInt(tempS[index++]); temp.resID = tempS[index++]; temp.rename = tempS[index++]; } if (Food.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddMenu.jsp?index=1" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { if (Food.addNewFood(temp)) { int id = Food.getFoodID(temp.ID); boolean flag = true; for (String s : names) { if (Image.addImage(s, Paths.foodImagePathStore + sepName + s, id)) { } else { flag = false; break; } } if (flag) { response.sendRedirect("./Admin/AddMenu.jsp?index=2" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { response.sendRedirect("./Admin/AddMenu.jsp?index=4" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } else { response.sendRedirect("./Admin/AddMenu.jsp?index=3" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } } catch (Exception e) { response.sendRedirect("./Admin/AddMenu.jsp?index=0" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } }
From source file:com.ephesoft.dcma.gwt.uploadbatch.server.UploadBatchImageServlet.java
private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, String currentBatchUploadFolderName) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempFile = null;/*from w w w.jav a 2 s .c om*/ InputStream instream = null; OutputStream out = null; String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder(); String uploadFileName = ""; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = ""; String uploadFilePath = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len = instream.read(buf); while (len > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error("Unable to create the upload folder." + e, e); printWriter.write("Unable to create the upload folder.Please try again."); } catch (IOException e) { LOG.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { LOG.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } } else { LOG.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName); printWriter.append("|"); printWriter.append("fileName:").append(uploadFileName); printWriter.append("|"); printWriter.flush(); }
From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * //from w ww .ja v a2 s. c om * 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); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } 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"; } System.out.println("111111222111111111"); 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.seer.datacruncher.profiler.spring.FileUploadController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request filePath = this.servletContext.getInitParameter("file-upload"); isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { return null; }/*from w ww. j av a 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(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(); 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.print("{success: true, file: \"" + fileName + "\"}"); // out.println("{\"file\": " + fileName + "}"); } } } catch (Exception ex) { System.out.println(ex); } return null; }
From source file:edu.iastate.airl.semtus.server.UploadServiceController.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {/* w w w .j a v a 2 s. c o m*/ List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) continue; String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName); // first clean-up the folder; we want no clutter on the server :-) String[] ls = new File(Utils.UPLOAD_DIRECTORY).list(); for (int idx = 0; idx < ls.length; idx++) { File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]); file.delete(); } if (uploadedFile.createNewFile()) { item.write(uploadedFile); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().print("The file was created successfully."); resp.flushBuffer(); } else { throw new IOException("The file already exists in repository."); } } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while creating the file : " + e.getMessage()); } } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }