Example usage for org.apache.commons.fileupload FileItem getName

List of usage examples for org.apache.commons.fileupload FileItem getName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getName.

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:dk.clarin.tools.userhandle.java

public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items,
        String parm) {//  w w  w  . ja  v a  2s  .c  o m
    logger.debug("parm:[" + parm + "]");
    String userHandle = "";
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        try {
            /*
            logger.debug("In try");
            DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
            / *
            *Set the size threshold, above which content will be stored on disk.
            * /
            fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
            / *
            * Set the temporary directory to store the uploaded files of size above threshold.
            * /
            logger.debug("making tmpDir in " + ToolsProperties.tempdir);
            File tmpDir = new File(ToolsProperties.tempdir);
            if(!tmpDir.isDirectory()) 
            {
            logger.debug("!tmpDir.isDirectory()");
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir + "\" as temporary directory, but this is not a valid directory.");
            }
            fileItemFactory.setRepository(tmpDir);
            * /
                    
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            logger.debug("Now uploadHandler.parseRequest");
            List items<FileItem> = uploadHandler.parseRequest(request);
            */
            logger.debug("items:" + items);
            Iterator<FileItem> itr = items.iterator();
            logger.debug("itr:" + itr);
            while (itr.hasNext()) {
                logger.debug("in loop");
                FileItem item = (FileItem) itr.next();
                /*
                * Handle Form Fields.
                */
                if (item.isFormField()) {
                    logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString());
                    if (item.getFieldName().equals(parm)) {
                        userHandle = item.getString();
                        logger.debug("Found " + parm + " = " + userHandle);
                        /*
                        if(userId == null && userHandle != null)
                        userId = userhandle.getUserId(request,userHandle);
                        if(userEmail == null && userId != null)
                        userEmail = userhandle.getEmailAddress(request,userHandle,userId);
                        */
                        break; // currently not interested in other fields than parm
                    }
                } else if (item.getName() != "") {
                    /*
                    * Write file to the ultimate location.
                    */
                    logger.debug("File = " + item.getName());
                    /* We don't handle file upload here
                    data = item.getName();
                    File file = new File(destinationDir,item.getName());
                    item.write(file);
                    */
                    logger.debug("FieldName = " + item.getFieldName());
                    logger.debug("Name = " + item.getName());
                    logger.debug("ContentType = " + item.getContentType());
                    logger.debug("Size = " + item.getSize());
                    logger.debug("DestinationDir = "
                            + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/);
                }
            }
        } catch (Exception ex) {
            logger.error("uploadHandler.parseRequest Exception");
        }
    } else {
        @SuppressWarnings("unchecked")
        Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames();

        for (Enumeration<String> e = parmNames; e.hasMoreElements();) {
            // Well, you don't get here AT ALL if enctype='multipart/form-data'
            String parmName = e.nextElement();
            logger.debug("parmName:" + parmName);
            String vals[] = request.getParameterValues(parmName);
            for (int j = 0; j < vals.length; ++j) {
                logger.debug("val:" + vals[j]);
            }
        }
    }
    logger.debug("value[" + parm + "]=" + userHandle);
    return userHandle;
}

From source file:com.wabacus.util.TestFileUploadInterceptor.java

/**
 * ??/??????//from   w w w.  jav a2  s .com
 */
public boolean beforeDisplayFileUploadPrompt(HttpServletRequest request, List lstFieldItems,
        Map<String, String> mFormAndConfigValues, String failedMessage, PrintWriter out) {
    if (lstFieldItems == null || lstFieldItems.size() == 0)
        return true;
    FileItem fItemTmp;
    StringBuffer fileNamesBuf = new StringBuffer();
    for (int i = 0; i < lstFieldItems.size(); i++) {
        fItemTmp = (FileItem) lstFieldItems.get(i);
        if (fItemTmp.isFormField())
            continue;//?
        fileNamesBuf.append(fItemTmp.getName()).append(";");
    }
    if (fileNamesBuf.charAt(fileNamesBuf.length() - 1) == ';')
        fileNamesBuf.deleteCharAt(fileNamesBuf.length() - 1);
    if (failedMessage != null && !failedMessage.trim().equals("")) {//
        out.println("<h4>??" + fileNamesBuf.toString() + "" + failedMessage
                + "</h4>");
    } else {//?
        out.println("<script language='javascript'>");
        out.println("alert('" + fileNamesBuf.toString() + "?');");

        String inputboxid = mFormAndConfigValues.get("INPUTBOXID");
        if (inputboxid != null && !inputboxid.trim().equals("")) {//?
            String name = mFormAndConfigValues.get("param_name");
            name = name + "[" + fileNamesBuf.toString() + "]";
            out.println("selectOK('" + name + "','name',null,true);");
        }
        out.println("</script>");
    }
    return false;//????
}

From source file:com.ephesoft.gxt.admin.server.DocumentTypeLearnFileServlet.java

@SuppressWarnings("unchecked")
private void attachFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    if (ServletFileUpload.isMultipartContent(req)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = batchSchemaService.getBaseFolderLocation() + File.separator
                + "tempLearnFile";
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdirs();
        } else {/*  w  w w .j a va 2 s  .  c  o m*/
            FileUtils.deleteContents(exportSerailizationFolderPath, false);
            exportSerailizationFolder.mkdirs();
        }
        String learnFileName = null;
        String pathToLearnFile = null;
        String learnFileExtension = null;
        List<FileItem> items;

        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    learnFileName = item.getName();

                    if (learnFileName != null) {
                        learnFileName = learnFileName.substring(learnFileName.lastIndexOf(File.separator) + 1);
                        learnFileExtension = learnFileName.substring(learnFileName.lastIndexOf(".") + 1);

                    }

                    pathToLearnFile = EphesoftStringUtil.concatenate(exportSerailizationFolderPath,
                            File.separator, learnFileName);

                    int numberOfPages = 0;

                    File learnedFile = new File(pathToLearnFile);
                    batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER);
                    documentType = req.getParameter(DocumentTypeConstants.DOCUMENT_TYPE_REQ_PARAMETER);

                    try {
                        item.write(learnedFile);
                        if (learnFileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) {
                            numberOfPages = PDFUtil.getPDFPageCount(pathToLearnFile);

                            converPDFTotiffFile(pathToLearnFile, numberOfPages);
                            copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName);

                        } else if (learnFileExtension.equalsIgnoreCase(FileType.TIF.getExtension())
                                || learnFileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) {
                            numberOfPages = TIFFUtil.getTIFFPageCount(pathToLearnFile);
                            if (numberOfPages != 1) {
                                convertMultiPageTiffToSinglePageTiff(pathToLearnFile, numberOfPages);
                                copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName);
                            } else {
                                copyFilesFromTempToLearnFolders(exportSerailizationFolderPath, learnFileName,
                                        FIRST_PAGE);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
        }
    }
}

From source file:com.nabla.wapp.server.basic.general.ImportService.java

@Override
public String executeAction(final HttpServletRequest request, final List<FileItem> sessionFiles)
        throws UploadActionException {
    final UserSession userSession = UserSession.load(request);
    if (userSession == null) {
        if (log.isTraceEnabled())
            log.trace("missing user session");
        throw new UploadActionException("permission denied");
    }//w ww.  j  a v a2s.com
    Assert.state(sessionFiles.size() == 1);
    try {
        for (FileItem file : sessionFiles) {
            if (file.isFormField())
                continue;
            if (log.isDebugEnabled()) {
                log.debug("field '" + file.getFieldName() + "': uploading " + file.getName());
                log.debug("field: " + file.getFieldName());
                log.debug("filename: " + file.getName());
                log.debug("content_type: " + file.getContentType());
                log.debug("size: " + file.getSize());
            }
            final Connection conn = db.getConnection();
            try {
                final PreparedStatement stmt = conn.prepareStatement(
                        "INSERT INTO import_data (field_name, file_name, content_type, length, content, userSessionId) VALUES(?,?,?,?,?,?);",
                        Statement.RETURN_GENERATED_KEYS);
                try {
                    stmt.setString(1, file.getFieldName());
                    stmt.setString(2, file.getName());
                    stmt.setString(3, file.getContentType());
                    stmt.setLong(4, file.getSize());
                    stmt.setString(6, userSession.getSessionId());
                    final InputStream fs = file.getInputStream();
                    try {
                        stmt.setBinaryStream(5, fs);
                        if (stmt.executeUpdate() != 1) {
                            if (log.isErrorEnabled())
                                log.error("failed to add imported file record");
                            throw new UploadActionException("internal error");
                        }
                        final ResultSet rsKey = stmt.getGeneratedKeys();
                        try {
                            rsKey.next();
                            final Integer id = rsKey.getInt(1);
                            if (log.isDebugEnabled())
                                log.debug(
                                        "uploading " + file.getName() + " successfully completed. id = " + id);
                            return id.toString();
                        } finally {
                            rsKey.close();
                        }
                    } finally {
                        fs.close();
                    }
                } catch (IOException e) {
                    if (log.isErrorEnabled())
                        log.error("error reading file " + file.getName(), e);
                    throw new UploadActionException("internal error");
                } finally {
                    Database.close(stmt);
                }
            } finally {
                // remove any orphan import records i.e. older than 48h (beware of timezone!)
                final Calendar dt = Util.dateToCalendar(new Date());
                dt.add(GregorianCalendar.DATE, -2);
                try {
                    Database.executeUpdate(conn, "DELETE FROM import_data WHERE created < ?;",
                            Util.calendarToSqlDate(dt));
                } catch (final SQLException __) {
                }
                Database.close(conn);
            }
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled())
            log.error("error uploading file", e);
        throw new UploadActionException("internal error");
    } finally {
        super.removeSessionFileItems(request);
    }
    return null;
}

From source file:com.rapidsist.portal.cliente.editor.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  ww  .  ja v a  2  s. c  o  m
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("PASO POR EL METODO doPost DEL SERVLET ConnectorServlet");
    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);

    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:fr.insalyon.creatis.vip.datamanager.server.rpc.FileUploadServiceImpl.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(CoreConstants.SESSION_USER);
    if (user != null && ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/* w  w w. ja  v  a 2 s . co  m*/
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            String fileName = null;
            FileItem fileItem = null;
            String path = null;
            String target = "uploadComplete";
            String operationID = "no-id";

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.getFieldName().equals("path")) {
                    path = item.getString();
                } else if (item.getFieldName().equals("file")) {
                    fileName = item.getName();
                    fileItem = item;
                } else if (item.getFieldName().equals("target")) {
                    target = item.getString();
                }
            }
            if (fileName != null && !fileName.equals("")) {

                boolean local = path.equals("local") ? true : false;
                String rootDirectory = DataManagerUtil.getUploadRootDirectory(local);
                fileName = new File(fileName).getName().trim().replaceAll(" ", "_");
                fileName = Normalizer.normalize(fileName, Normalizer.Form.NFD)
                        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
                File uploadedFile = new File(rootDirectory + fileName);

                try {
                    fileItem.write(uploadedFile);
                    response.getWriter().write(fileName);

                    if (!local) {
                        // GRIDA Pool Client
                        logger.info("(" + user.getEmail() + ") Uploading '" + uploadedFile.getAbsolutePath()
                                + "' to '" + path + "'.");
                        GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
                        operationID = client.uploadFile(uploadedFile.getAbsolutePath(),
                                DataManagerUtil.parseBaseDir(user, path), user.getEmail());

                    } else {
                        operationID = fileName;
                        logger.info(
                                "(" + user.getEmail() + ") Uploaded '" + uploadedFile.getAbsolutePath() + "'.");
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }

            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent." + target + ") parent." + target + "('" + operationID + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();

        } catch (FileUploadException ex) {
            logger.error(ex);
        }
    }
}

From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www .j  a v  a  2s . 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");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    HttpSession aSession = request.getSession();
    try {
        Person pers = (Person) aSession.getAttribute("person");
        String primaryKey = pers.getAccount().getEmail();
        PersonManager aPerson = PersonManager.getInstance();
        Person person = aPerson.getStudent(primaryKey);
        ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance();
        out = response.getWriter();

        String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula());
        File subfolderFile = new File(studentSubfolderPath);
        if (!subfolderFile.exists()) {
            subfolderFile.mkdir();
        }

        isMultipart = ServletFileUpload.isMultipartContent(request);
        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 CVPath = "", ATPath = "";

        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("cv")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf");
                    CVPath = fileToStore.getAbsolutePath();
                } else if (fieldName.equals("doc")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf");
                    ATPath = fileToStore.getAbsolutePath();
                }
                fi.write(fileToStore);

                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());

            }

        }

        if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) {
            message.setMessage("status", 1);
        } else {
            message.setMessage("status", 0);
        }
        aSession.setAttribute("message", message);
        response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp");
        //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp");
        //dispatcher.forward(request,response);
    } catch (Exception ex) {
        Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex);
        message.setMessage("status", -1);
        aSession.setAttribute("message", message);
    } finally {
        out.close();
    }
}

From source file:com.duroty.application.files.actions.UploadAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {/*from  w  w  w  .  j  a  v a2 s .  c  om*/
        boolean isMultipart = FileUpload.isMultipartContent(request);

        Store storeInstance = getStoreInstance(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector files = 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());

                            files.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            if (files.size() > 0) {
                //Integer label = new Integer((String) fields.get("label"));
                storeInstance.send(files, 0, Charset.defaultCharset().displayName());
            }
        } 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:controller.uploadImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww  w.j  a v  a 2s. 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, Exception {
    response.setContentType("text/html;charset=UTF-8");

    //ArrayList<String> ls=new ArrayList();

    try (PrintWriter out = response.getWriter()) {
        //if (!ServletFileUpload.isMultipartContent(request)) {
        //if not, we stop here
        //PrintWriter writer = response.getWriter();
        //writer.println("Error: Form must has enctype=multipart/form-data.");
        //writer.flush();
        //return;

        //}
        // configures upload settings
        HttpSession ssn = request.getSession();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // parses the request's content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        // saves the file on disk
                        if (storeFile.exists()) {

                            ssn.setAttribute("uploadMsg", "File exists");

                            response.sendRedirect("register.htm?name=index");

                        } else {
                            //if(item.isInMemory())
                            item.write(storeFile);
                            ssn.setAttribute("imgname", storeFile.getName());
                            ssn.setAttribute("uploadMsg", "File uploded");
                            response.sendRedirect("register.htm?name=null");

                        }

                    } else {

                        ssn.setAttribute(item.getFieldName(), item.getString());

                    }
                }
            }
        } catch (Exception ex) {
            ssn.setAttribute("uploadMsg", ex.getMessage());
            response.sendRedirect("register.htm?name=index");
        }

    }

}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request/*from w  w  w .j  a  v  a2s .  c  o  m*/
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}