List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.baobao121.baby.common.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * //from w w w.j a va 2 s.co m * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<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 commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { 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); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.scooterframework.web.controller.ActionControl.java
/** * Returns a list of upload files. Each item in the list is an instance * of <tt>java.io.File</tt> instance. * //from w w w . j av a2 s. co m * @param fileRepository * @return a list of upload files (File) * @throws Exception */ public static List<File> getUploadFilesAsFiles(String fileRepository) throws Exception { List<File> files = new ArrayList<File>(); List<FileItem> items = prepareFileItems(); for (FileItem item : items) { if (!item.isFormField() && !"".equals(item.getName())) { File f = new File(fileRepository + File.separator + item.getName()); files.add(f); } } return files; }
From source file:com.ephesoft.dcma.gwt.admin.bm.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, DeploymentService deploymentService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;//from ww w.java 2 s .co m InputStream instream = null; OutputStream out = null; String zipWorkFlowName = BatchClassManagementConstants.EMPTY_STRING, tempOutputUnZipDir = BatchClassManagementConstants.EMPTY_STRING, systemFolderPath = BatchClassManagementConstants.EMPTY_STRING; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = BatchClassManagementConstants.EMPTY_STRING; String zipPathname = BatchClassManagementConstants.EMPTY_STRING; List<FileItem> items; try { items = (List<FileItem>) upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField() && "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE]; 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 export folder." + e, e); printWriter.write("Unable to create the export 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 { IOUtils.closeQuietly(out); IOUtils.closeQuietly(instream); } } } } catch (FileUploadException e) { LOG.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { LOG.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); systemFolderPath = importBatchClass.getSystemFolder(); if (systemFolderPath == null) { systemFolderPath = BatchClassManagementConstants.EMPTY_STRING; } } catch (Exception e) { tempZipFile.delete(); LOG.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { IOUtils.closeQuietly(serializableFileStream); } } else { LOG.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriterMethod(printWriter, zipWorkFlowName, tempOutputUnZipDir, systemFolderPath, uncList, isWorkflowDeployed, isWorkflowEqual); }
From source file:com.softwarementors.extjs.djn.test.ManualFormUploadSupportTest.java
@DirectFormPostMethod public Result djnform_test_sendFilesManually(Map<String, String> formParameters, Map<String, FileItem> fileFields) { assert formParameters != null; assert fileFields != null; Result r = new Result(); FileItem file1 = fileFields.get("fileUpload1"); FileItem file2 = fileFields.get("fileUpload2"); if (fileFields.size() != 2 || file1 == null || file2 == null) { throw new DirectTestFailedException("Unexpected error receiving file fields"); }/*from www. j av a 2 s.c o m*/ try { r.file1Field = file1.getFieldName(); r.file1Name = file1.getName(); if (!r.file1Name.equals("")) { r.file1Text = IOUtils.toString(file1.getInputStream()); file1.getInputStream().close(); } r.file2Field = file2.getFieldName(); r.file2Name = file2.getName(); if (!r.file2Name.equals("")) { r.file2Text = IOUtils.toString(file2.getInputStream()); file2.getInputStream().close(); } } catch (IOException e) { throw new DirectTestFailedException("Test failed", e); } return r; }
From source file:controlador.Carga.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . j a va 2 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(); DiskFileItemFactory ff = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(ff); List items = null; File archivo = null; try { items = sfu.parseRequest(request); } catch (FileUploadException ex) { out.print(ex.getMessage()); } for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { // archivo = new File(this.getServletContext().getRealPath("/datos/") +"/" + item.getName()); archivo = new File( "/var/lib/openshift/55672e834382ec6dbc00010d/jbossews/webapps/" + item.getName()); try { item.write(archivo); } catch (Exception ex) { out.print(ex.getMessage()); } } } out.print("Se subio el archivo" + this.getServletContext().getRealPath("/datos/")); CargaInicial cargar; try { cargar = new CargaInicial(); String ubicacion = archivo.toString(); cargar.cargar(ubicacion); } catch (MiExcepcion ex) { out.print("Ha ocurrido un error de conexin a base de datos."); } }
From source file:crds.pub.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<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 .j av a2 s . c o m*/ * */ @SuppressWarnings({ "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id + currentFolderStr + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { 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); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:it.unisa.tirocinio.servlet.UploadInformationFilesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww 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, JSONException { try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); StudentDBOperation getSerialNumberObj = new StudentDBOperation(); ConcreteStudent aStudent = null; String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String studentSubfolderPath = filePath; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (fieldName.equals("cvfile")) { fileToStore = new File(studentSubfolderPath + fileSeparator + "CV.pdf"); } else if (fieldName.equals("examsfile")) { fileToStore = new File(studentSubfolderPath + fileSeparator + "ES.pdf"); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); aStudent = getSerialNumberObj.getSerialNumberbyFK_Account(Integer.parseInt(fi.getString())); serialNumber = reverseSerialNumber(aStudent.getPrimaryKey()); studentSubfolderPath += fileSeparator + serialNumber; new File(studentSubfolderPath).mkdir(); } } message.put("status", 1); out.print(message.toString()); } catch (IOException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (FileUploadException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:com.ait.tooling.server.core.servlet.FileUploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("STARTING UPLOAD"); try {//from w ww .ja va2s .c om DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); fileUpload.setSizeMax(FILE_SIZE_LIMIT); List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { logger.info("Received form field"); logger.info("Name: " + item.getFieldName()); logger.info("Value: " + item.getString()); } else { logger.info("Received file"); logger.info("Name: " + item.getName()); logger.info("Size: " + item.getSize()); } if (false == item.isFormField()) { if (item.getSize() > FILE_SIZE_LIMIT) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds limit"); return; } // Typically here you would process the file in some way: // InputStream in = item.getInputStream(); // ... if (false == item.isInMemory()) { item.delete(); } } } } catch (Exception e) { logger.error("Throwing servlet exception for unhandled exception", e); throw new ServletException(e); } }
From source file:com.duroty.application.mail.actions.SaveDraftAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try {/*from ww w . ja v a2s. co m*/ boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { Map fields = new HashMap(); Vector attachments = new Vector(); //Parse the request List items = diskFileUpload.parseRequest(request); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); attachments.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } String body = ""; if (fields.get("taBody") != null) { body = (String) fields.get("taBody"); } else if (fields.get("taReplyBody") != null) { body = (String) fields.get("taReplyBody"); } Preferences preferencesInstance = getPreferencesInstance(request); Send sendInstance = getSendInstance(request); String mid = (String) fields.get("mid"); sendInstance.saveDraft(mid, Integer.parseInt((String) fields.get("identity")), (String) fields.get("to"), (String) fields.get("cc"), (String) fields.get("bcc"), (String) fields.get("subject"), body, attachments, preferencesInstance.getPreferences().isHtmlMessage(), Charset.defaultCharset().displayName(), (String) fields.get("priority")); } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
From source file:inet.util.FileStorage.java
public List<File> storage(String key) throws Exception { List<FileItem> fileItems = multipartRequest.getFileItems(key); List<File> files = new ArrayList<File>(); File file;// ww w. j a va 2 s.co m if (fileItems != null) { for (FileItem fileItem : fileItems) { if (fileItem == null || fileItem.getContentType().equals("application/octet-stream")) { return null; } else { file = new File(); int read = 0; byte[] bytes = new byte[1024]; String fileName = targe + System.currentTimeMillis() + fileItem.getName(); String realFile = realPath + fileName; OutputStream outputStream = new FileOutputStream(realFile); InputStream inputStream = fileItem.getInputStream(); while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.close(); inputStream.close(); file.setUrl(realUri + fileName); } files.add(file); } return files; } else { return null; } }