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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:Ctrl.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www .  java2 s . 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();

    try {

        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here

            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
        // configures upload settings
        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();
        }

        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
                    item.write(storeFile);

                    request.setAttribute("ten", fileName);
                    request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName);
                    request.setAttribute("message",
                            "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName);
                }
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    // redirects client to message page
    getServletContext().getRequestDispatcher("/Product.jsp").forward(request, response);

}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP/*from  ww  w.j  ava 2 s.c  om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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 req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/plain;charset=gbk");

    res.setContentType("text/html; charset=utf-8");
    PrintWriter pw = res.getWriter();
    try {
        //initialize the prefix url
        if (prefix_url == null) {
            //                String hostname = req.getServerName ();
            //                int port = req.getServerPort ();
            //                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            //updated by Ziheng - on 8/27/2015
            //This method should be used everywhere.
            int num = req.getRequestURI().indexOf("/PACS");
            String prefix = req.getRequestURI().substring(0, num + "/PACS".length()); //in case there is something before PACS
            prefix_url = req.getScheme() + "://" + req.getServerName()
                    + ("http".equals(req.getScheme()) && req.getServerPort() == 80
                            || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? ""
                                    : ":" + req.getServerPort())
                    + prefix + "/" + relativePath + "/";
        }
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        String head = "<head>" + "<title>File Uploading Response</title>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
                + "<script type=\"text/javascript\" src=\"js/TaskGridTool.js\"></script>" + "</head>";
        pw.println(head);
        pw.println("<body>");

        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold  2M 
        //extend to 2M - updated by ziheng - 9/25/2014
        diskFactory.setSizeThreshold(2 * 1024);
        // repository 
        diskFactory.setRepository(new File(tempPath));

        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        // 2M
        upload.setSizeMax(2 * 1024 * 1024);
        // HTTP
        List fileItems = upload.parseRequest(req);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item, pw);
            } else {
                processUploadFile(item, pw);
            }
        } // end while()
          //add some buttons for further process
        pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
        pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
        pw.println("</body>");
        pw.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
        pw.println("ERR:" + e.getClass().getName() + ":" + e.getLocalizedMessage());
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:filter.MultipartRequestFilter.java

/**
 * Parse the given HttpServletRequest. If the request is a multipart request, then all multipart
 * request items will be processed, else the request will be returned unchanged. During the
 * processing of all multipart request items, the name and value of each regular form field will
 * be added to the parameterMap of the HttpServletRequest. The name and File object of each form
 * 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.
 * @param request The HttpServletRequest to be checked and parsed as multipart request.
 * @return The parsed HttpServletRequest.
 * @throws ServletException If parsing of the given HttpServletRequest fails.
 *//*  www .j  a v a  2s. c o m*/
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException {

    // Check if the request is actually a multipart/form-data request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        // If not, then return the request unchanged.
        return request;
    }

    // Prepare the multipart request items.
    // I'd rather call the "FileItem" class "MultipartItem" instead or so. What a stupid name ;)
    List<FileItem> multipartItems = null;

    try {
        // Parse the multipart request items.
        multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        // Note: we could use ServletFileUpload#setFileSizeMax() here, but that would throw a
        // FileUploadException immediately without processing the other fields. So we're
        // checking the file size only if the items are already parsed. See processFileField().
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request: " + e.getMessage());
    }

    // Prepare the request parameter map.
    Map<String, String[]> parameterMap = new HashMap<String, String[]>();

    // Loop through multipart request items.
    for (FileItem multipartItem : multipartItems) {
        if (multipartItem.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            processFormField(multipartItem, parameterMap);
        } else {
            // Process form file field (input type="file").
            processFileField(multipartItem, request);
        }
    }

    // Wrap the request with the parameter map which we just created and return it.
    return wrapRequest(request, parameterMap);
}

From source file:graphvis.webui.servlets.UploadServlet.java

/**
  * This method receives POST from the index.jsp page and uploads file, 
  * converts into the correct format then places in the HDFS.
  *//*from   w w w  .java 2 s  .co  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        response.setStatus(403);
        return;
    }

    File tempDirFileObject = new File(Configuration.tempDirectory);

    // Create/remove temp folder
    if (tempDirFileObject.exists()) {
        FileUtils.deleteDirectory(tempDirFileObject);
    }

    // (Re-)create temp directory
    tempDirFileObject.mkdir();
    FileUtils.copyFile(
            new File(getServletContext()
                    .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")),
            new File(Configuration.tempDirectory
                    + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar"));
    FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")),
            new File(Configuration.tempDirectory + "/dist-graphvis.jar"));

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(Configuration.MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(Configuration.MAX_REQUEST_SIZE);

    String fileName = "";
    try {
        // Parse the request
        List<?> items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                String filePath = Configuration.tempDirectory + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    throw new ServletException(ex);
                }
            }
        }

        String fullFilePath = Configuration.tempDirectory + File.separator + fileName;

        String extension = FilenameUtils.getExtension(fullFilePath);

        // Load Files intoHDFS
        // (This is where we do the parsing.)
        loadIntoHDFS(fullFilePath, extension);

        getServletContext().setAttribute("fileName", new File(fullFilePath).getName());
        getServletContext().setAttribute("fileExtension", extension);

        // Displays fileUploaded.jsp page after upload finished
        getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    }

}

From source file:juzu.plugin.upload.impl.UploadPlugin.java

public void invoke(Request request) {

    ////  www.j a  v a 2s .co m
    final ClientContext clientContext = request.getClientContext();

    //
    if (clientContext != null) {
        String contentType = clientContext.getContentType();
        if (contentType != null) {
            if (contentType.startsWith("multipart/")) {

                //
                org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() {
                    public String getCharacterEncoding() {
                        return clientContext.getCharacterEncoding();
                    }

                    public String getContentType() {
                        return clientContext.getContentType();
                    }

                    public int getContentLength() {
                        return clientContext.getContentLenth();
                    }

                    public InputStream getInputStream() throws IOException {
                        return clientContext.getInputStream();
                    }
                };

                //
                FileUpload upload = new FileUpload(new DiskFileItemFactory());

                //
                try {
                    List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx);
                    HashMap<String, RequestParameter> parameters = new HashMap<String, RequestParameter>();
                    for (FileItem file : list) {
                        String name = file.getFieldName();
                        if (file.isFormField()) {
                            RequestParameter parameter = parameters.get(name);
                            if (parameter != null) {
                                parameter = parameter.append(new String[] { file.getString() });
                            } else {
                                parameter = RequestParameter.create(name, file.getString());
                            }
                            parameter.appendTo(parameters);
                        } else {
                            ControlParameter parameter = request.getMethod().getParameter(name);
                            if (parameter instanceof ContextualParameter
                                    && FileItem.class.isAssignableFrom(parameter.getType())) {
                                request.setArgument(parameter, file);
                            }
                        }
                    }

                    // Keep original parameters that may come from the request path
                    for (RequestParameter parameter : request.getParameters().values()) {
                        if (!parameters.containsKey(parameter.getName())) {
                            parameter.appendTo(parameters);
                        }
                    }

                    // Redecode phase arguments from updated request
                    Method<?> method = request.getMethod();
                    Map<ControlParameter, Object> arguments = method.getArguments(parameters);

                    // Update with existing contextual arguments
                    for (Map.Entry<ControlParameter, Object> argument : request.getArguments().entrySet()) {
                        if (argument.getKey() instanceof ContextualParameter) {
                            arguments.put(argument.getKey(), argument.getValue());
                        }
                    }

                    // Replace all arguments
                    request.setArguments(arguments);
                } catch (FileUploadException e) {
                    throw new UndeclaredThrowableException(e);
                }
            }
        }
    }

    //
    request.invoke();
}

From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//from ww  w  . j  a v  a  2s. c  o  m
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (!fileItem.isFormField()) {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext)
                                && !"PNG".equalsIgnoreCase(ext)) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR,
                                    "Invalid image. Please upload JPG or PNG file");
                            return (new MyProfileAction().execute(request, response));
                        }
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return (new MyProfileAction().execute(request, response));
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new MyProfileAction().execute(request, response));
            }
            if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file");
                return (new MyProfileAction().execute(request, response));
            }

            User user = loggedInUser;
            user.setProfilePicture(file);
            UserDAO.getInstance().setProfilePicture(user);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "", "Profile picture update"));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
    request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully");
    return (new MyProfileAction().execute(request, response));
}

From source file:massbank.FileUpload.java

/**
 * t@CAbv??[h//from   w w  w  .j a  v a2  s .co m
 * multipart/form-datat@CAbv??[h
 * s??nullp
 * @return Abv??[ht@C?MAP<t@C, Abv??[h>
 */
@SuppressWarnings("unchecked")
public HashMap<String, Boolean> doUpload() {

    if (fileItemList == null) {
        try {
            fileItemList = (List<FileItem>) parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }
    }

    upFileMap = new HashMap<String, Boolean>();
    for (FileItem fItem : fileItemList) {

        // t@CtB?[h??
        if (!fItem.isFormField()) {

            String key = "";
            boolean val = false;

            // t@C?ipX????j
            String filePath = (fItem.getName() != null) ? fItem.getName() : "";

            // t@C?imt@C?j
            String fileName = (new File(filePath)).getName();
            int pos = fileName.lastIndexOf("\\");
            fileName = fileName.substring(pos + 1);
            pos = fileName.lastIndexOf("/");
            fileName = fileName.substring(pos + 1);

            // t@CAbv??[h
            if (!fileName.equals("")) {
                key = fileName;
                File upFile = new File(outPath + "/" + fileName);
                try {
                    fItem.write(upFile);
                    val = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    upFile.delete();
                }
            }
            upFileMap.put(key, val);
        }
    }

    return upFileMap;
}

From source file:MyPack.AddAuctionItems.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w .j  av  a2s.  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 {
    config = getServletConfig();
    System.out.println("Inside insert code");
    try {

        session = request.getSession();
        int regid = (Integer) session.getAttribute("regid");
        String itemname = "";
        int itemprice = 0;
        String date = "";
        String time = "";
        int catid = 0;
        String itempic = "";

        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 (FileUploadException ex) {
                Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("itemname")) {
                        itemname = value;
                        //                      count1=1;
                        System.out.println("name = " + itemname);
                    }
                    if (name.equals("itemprice")) {
                        itemprice = Integer.parseInt(value);
                        //                         count2=2;
                        System.out.println("price = " + itemprice);
                    }
                    if (name.equals("itemdate")) {
                        date = value;
                        //                         count5=5;
                        System.out.println("date = " + date);
                    }
                    if (name.equals("itemtime")) {
                        time = value;
                        // count3=3;
                        System.out.println("time = " + time);
                    }

                    if (name.equals("selectedRecord")) {
                        //                     count4=4;
                        catid = Integer.parseInt(value);
                        System.out.println("emp_emailid = " + catid);
                    }

                } else {
                    try {

                        itempic = item.getName();
                        System.out.println("itemName============" + itempic);
                        File savedFile = new File(
                                config.getServletContext().getRealPath("/") + "../../web/upimage\\" + itempic);
                        //                            System.out.println(config.getServletContext().getRealPath("/") + "upimage\\" + itempic);
                        item.write(savedFile);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        PrintWriter out = response.getWriter();
        DBConnection Db = new DBConnection();
        String sql = "insert into tb_auction_items values(null,'" + itemname + "','" + itemprice + "','" + date
                + "','" + time + "','0','" + catid + "','" + regid + "','" + itempic + "')";
        System.out.println(sql);
        int row = Db.UpdateQuery(sql);
        if (row > 0) {
            out.print("<script>alert('Successulyy added');</script>");
            response.sendRedirect("viewitems");
            // request.getRequestDispatcher("viewitems").include(request, response);

        } else {
            request.getRequestDispatcher("AddAuctionItemss.jsp").forward(request, response);
            out.print("<script>alert('Failed to Update');</script>");
        }
        Db.Close();
    } catch (Exception ex) {
        Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.beetle.framework.web.controller.UploadController.java

/**
 * use the overdue upload package/*from  w ww. ja v a  2 s  . c  o  m*/
 * 
 * @param webInput
 * @param request
 * @return
 * @throws ControllerException
 */
private View doupload(WebInput webInput, HttpServletRequest request) throws ControllerException {
    UploadForm fp = null;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    List<?> fileItems = null;
    boolean openApiCase = false;
    try {
        IUpload upload = (IUpload) webInput.getRequest().getAttribute("UPLOAD_CTRL_IOBJ");
        if (upload == null) {
            logger.debug("get upload from :{}", webInput.getControllerName());
            String ctrlimpName = (String) webInput.getRequest().getAttribute(CommonUtil.controllerimpclassname);
            if (ctrlimpName != null)
                upload = UploadFactory.getUploadInstance(webInput.getControllerName(), ctrlimpName); // 2007-03-21
            serviceInject(upload);
        }
        if (upload == null) {
            String uploadclass = webInput.getParameter("$upload");
            if (uploadclass == null || uploadclass.trim().length() == 0) {
                throw new ControllerException("upload dealer can't not found!");
            }
            openApiCase = true;
            String uploadclass_ = ControllerFactory.composeClassImpName(webInput.getRequest(), uploadclass);
            logger.debug("uploadclass:{}", uploadclass);
            logger.debug("uploadclass_:{}", uploadclass_);
            upload = UploadFactory.getUploadInstance(uploadclass, uploadclass_);
            serviceInject(upload);
        }
        logger.debug("IUpload:{}", upload);
        long sizeMax = webInput.getParameterAsLong("sizeMax", 0);
        if (sizeMax == 0) {
            sfu.setSizeMax(IUpload.sizeMax);
        } else {
            sfu.setSizeMax(sizeMax);
        }
        int sizeThreshold = webInput.getParameterAsInteger("sizeThreshold", 0);
        if (sizeThreshold == 0) {
            factory.setSizeThreshold(IUpload.sizeThreshold);
        } else {
            factory.setSizeThreshold(sizeThreshold);
        }
        Map<String, String> fieldMap = new HashMap<String, String>();
        List<FileObj> fileList = new ArrayList<FileObj>();
        fileItems = sfu.parseRequest(request);
        Iterator<?> i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                fieldMap.put(fi.getFieldName(), fi.getString());
            } else {
                fileList.add(new FileObj(fi));
            }
        }
        fp = new UploadForm(fileList, fieldMap, request, webInput.getResponse());
        View view = upload.processUpload(fp);
        if (view.getViewname() == null || view.getViewname().trim().equals("")) {
            // view.setViewName(AbnormalViewControlerImp.abnormalViewName);
            //
            if (openApiCase) {
                return view;
            }
            UpService us = new UpService(view);
            return us.perform(webInput);
        }
        return view;
    } catch (Exception ex) {
        logger.error("upload", ex);
        throw new ControllerException(WebConst.WEB_EXCEPTION_CODE_UPLOAD, ex);
    } finally {
        if (fileItems != null) {
            fileItems.clear();
        }
        if (fp != null) {
            fp.clear();
        }
        sfu = null;
    }
}

From source file:controllers.FrameworkController.java

private void adicionarOuEditarFramework() throws IOException {
    String nome, genero, paginaOficial, id, descricao, caminhoLogo;
    int idLinguagem = -1;
    genero = nome = paginaOficial = descricao = id = caminhoLogo = "";

    File file;/*from ww w. j a  va  2  s  . c  o m*/
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName.lastIndexOf("\\") >= 0) {
                        //String name = fileName.substring(fileName.lastIndexOf("\\"), fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    } else {
                        //String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    }
                    caminhoLogo = file.getName();
                    fi.write(file);
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "genero":
                        genero = valor;
                        break;
                    case "pagina_oficial":
                        paginaOficial = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "linguagem":
                        idLinguagem = Integer.parseInt(valor);
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Framework framework = dao.select(Integer.parseInt(id));

        framework.setDescricao(descricao);
        framework.setGenero(genero);
        framework.setIdLinguagem(idLinguagem);
        framework.setNome(nome);
        framework.setPaginaOficial(paginaOficial);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + framework.getCaminhoLogo());
            imagemAntiga.delete();

            framework.setCaminhoLogo(caminhoLogo);
        }

        dao.update(framework);

    } else {
        Framework framework = new Framework(nome, descricao, genero, paginaOficial, idLinguagem, caminhoLogo);

        dao.insert(framework);
    }

    response.sendRedirect("frameworks.jsp");
    //response.getWriter().print("<script>window.location.href='frameworks.jsp';</script>");
}