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:com.shyshlav.functions.filework.download_image.java

public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8"); //  
    response.setCharacterEncoding("UTF-8");
    filePath = request.getSession().getServletContext().getInitParameter("avathars");
    System.out.println(filePath);
    isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipart);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (!isMultipart) {
        return "  ";
    }//from ww  w  .  j  a v  a2s . 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("c:\test"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        //String name,String password,String email,String surname,String link_to_image,String about_me,String id
        String name = null;
        String password = null;
        String re_password = null;
        String surname = null;
        String about_me = null;
        String id = null;
        String link_to_server = null;
        String email = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                String fieldname = fi.getFieldName();
                String fieldvalue = fi.getString();
                if (fieldname.equals("name")) {
                    name = fi.getString("UTF-8");
                } else if (fieldname.equals("surname")) {
                    surname = fi.getString("UTF-8");
                } else if (fieldname.equals("password")) {
                    password = fi.getString("UTF-8");
                } else if (fieldname.equals("re_password")) {
                    re_password = fi.getString("UTF-8");
                } else if (fieldname.equals("about_me")) {
                    about_me = fi.getString("UTF-8");
                } else if (fieldname.equals("id")) {
                    id = fi.getString("UTF-8");
                } else if (fieldname.equals("email")) {
                    email = fi.getString("UTF-8");
                }
                System.out.println(fieldname + fieldvalue);
                if (fieldname == null || fieldvalue == null) {
                    return "? ? ? ";
                }
            }
            if (!fi.isFormField()) {
                if (!password.equals(re_password)) {
                    System.out.println(password + " - " + re_password);
                    return "  ?";
                }
                // Get the uploaded file parameters
                String fileName = email + ".png";
                link_to_server = "/musicbox/avathars/" + email + ".png".trim();
                // 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);
                System.out.println("Uploaded Filename: " + filePath + fileName);
            }
        }
        System.out.println(link_to_server);
        updateUser um = new updateUser();
        um.updateUser(name, password, surname, link_to_server, about_me, id);
    } catch (Exception ex) {
        System.out.println(ex);
        return "    1 ";
    }
    return "ok";
}

From source file:corpixmgr.handler.CorpixPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request// w w w.j a v a2  s  .c o  m
 */
protected void parseImportParams(HttpServletRequest request) throws CorpixException {
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //System.out.println("Parsing import params");
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        String contents = item.getString("UTF-8");
                        processField(fieldName, contents);
                    }
                } else if (item.getName().length() > 0) {
                    fileName = item.getName();
                    InputStream is = item.getInputStream();
                    ByteArrayOutputStream bh = new ByteArrayOutputStream();
                    while (is.available() > 0) {
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        bh.write(b);
                    }
                    fileData = bh.toByteArray();
                }
            }
        } else {
            Map tbl = request.getParameterMap();
            Set<String> keys = tbl.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String[] values = (String[]) tbl.get(key);
                for (int i = 0; i < values.length; i++)
                    processField(key, values[i]);
            }
        }
    } catch (Exception e) {
        throw new CorpixException(e);
    }
}

From source file:lcn.module.oltp.web.common.base.MultipartResolver.java

/**
 * multipart?  parsing? .//from  w w  w  . j  ava2s.  co  m
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    //   Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    //   Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }
    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters, multipartParameters);

    //   return new MultipartParsingResult(multipartFiles, multipartParameters);
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {// w ww .  ja va2 s.com
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + fileName);
                        //System.out.println("caminho: " + saveTo.toString() );
                        try {
                            fileItem.write(saveTo);
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

private void processFormField(FileItem item) {
    // Process a regular form field
    if (item.isFormField()) {
        String name = item.getFieldName();
        String value = item.getString();
        log("name: " + name + " value: " + value);
    }//w w  w  . java 2s . c  o m
}

From source file:net.sourceforge.jwebunit.tests.util.ParamsServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write(HtmlHelper.getStart("Submitted parameters"));
    out.write("<h1>Submitted parameters</h1>\n<p>Params are:<br/>");
    /*/*from ww w .j  av a  2 s  . c om*/
     * Prints POST and GET parameters as name=[value1[,value2...]] separated
     * by <BR/>
     */

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        // 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
        List /* FileItem */ items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        String ref = null;
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                out.write(" " + item.getFieldName() + "=[" + item.getString());
                if (item.getFieldName().equals("myReferer")) {
                    ref = item.getString();
                }
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                out.write(" " + fieldName + "=[" + fileName + "{" + new String(item.get()) + "}");

            }
            if (iter.hasNext()) {
                out.write("]<br/>\n");
            }
        }
        out.write("]</p>\n");
        out.write(HtmlHelper.getLinkParagraph("return", ref));
    } else {
        java.util.Enumeration params = request.getParameterNames();
        for (; params.hasMoreElements();) {
            String p = params.nextElement().toString();
            String[] v = request.getParameterValues(p);
            out.write(p + "=[");
            int n = v.length;
            if (n > 0) {
                out.write(v[0] != null ? v[0] : "");
                for (int i = 1; i < n; i++) {
                    out.write("," + (v[i] != null ? v[i] : ""));
                }
            }
            if (params.hasMoreElements()) {
                out.write("]<br/>\n");
            }
        }
        out.write("]</p>\n");
        String ref = request.getHeader("Referer");
        if (ref == null) {
            if (request.getParameterValues("myReferer") != null) {
                ref = request.getParameterValues("myReferer")[0];
            }
        }
        out.write(HtmlHelper.getLinkParagraph("return", ref));
    }
    out.write(HtmlHelper.getEnd());
}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www.j av  a 2 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 {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:au.edu.unimelb.news.servlet.ImportServlet.java

/**
 * Reads all user input related to creating a new agenda item and creates the agenda item.
 *///from  w  w  w .  j a v a  2 s  . c  om
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    User user = UserHelper.getUser(request);
    response.setContentType("text/html");
    PrintWriter out = new PrintWriter(response.getOutputStream());
    LayoutHelper.headerTitled(out, "Import");
    LayoutHelper.menubar(out, user);

    out.println("<div id=\"breadcrumbs\">");
    out.println("<a href=\"http://www.unimelb.edu.au\">University home</a> &gt;");
    out.println("<a href=\"" + Configuration.appPrefix + "/\">University News</a> &gt;");
    out.println("Document Import");
    out.println("</div>");

    out.println("<div id=\"content\">");
    out.println("<h2>Importing</h2>");

    //out.flush();

    /*
     *  This chunk calls the Jakarta Commons Fileupload component to
     *  process the file upload information.
     */
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    /*
     * Use the Jakarta Commons Fileupload component to read the
     * field variables.
     */
    try {
        out.println("<ul>");
        String filename = "";
        for (FileItem field : items) {
            if (!field.isFormField()) {
                filename = field.getName();
                if (filename.contains("/"))
                    filename = filename.substring(filename.lastIndexOf('/') + 1);
                if (filename.contains("\\"))
                    filename = filename.substring(filename.lastIndexOf('\\') + 1);
                int no = random.nextInt();
                if (no < 1)
                    no = -no;
                if (filename.length() > 0 && field.getSize() > 0
                        && field.getFieldName().equals("import_file")) {
                    ArticleImport helper = new ArticleImport(new ArticleImportResponder(user, out));
                    helper.process(field.getInputStream(), user);
                }
            }
        }
        out.println("</ul>");
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    out.println("File upload processing complete.");

    out.println("</div>");
    LayoutHelper.footer(out);

    out.flush();
    out.close();
}

From source file:by.iharkaratkou.TestServlet.java

public String processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filenameTimestamp = "";

    try {// w  w w  .  ja v a 2  s.co m
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (!ismultipart) {
            System.out.println("ismultipart is false");
        } else {
            System.out.println("ismultipart is true");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {

                items = upload.parseRequest(request);
            } catch (Exception e) {
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {

                } else {
                    String itemname = item.getName();
                    if ((itemname == null || itemname.equals(""))) {
                        continue;
                    }
                    String filename = FilenameUtils.getName(itemname);
                    System.out.println(filename);
                    File f = checkExist(filename);
                    item.write(f);
                    if (f.getName().contains(".xlsx")) {
                        filenameTimestamp = f.getName();
                    }
                }
            }
        }

    } catch (Exception e) {

    } finally {
        out.close();
    }
    return filenameTimestamp;
}

From source file:com.app.uploads.ImageUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from www  .  j av a2 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 out = response.getWriter();
    String[] Fielname = new String[2];
    CallableStatement pro;
    int i = 0;
    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        if (i == 0) {
                            Fielname[0] = new String(b);
                        } else {
                            Fielname[1] = new String(b);
                        }
                        i++;
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT(?,?,?)}");
                pro.setString(1, name);
                pro.setString(2, Fielname[0]);
                pro.setString(3, Fielname[1]);
                pro.executeQuery();
                pro.close();
                connect.close();
                request.setAttribute("message", "File Uploaded Successfully");
                request.setAttribute("name", name);
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
        out.print("Description:" + Fielname[0]);
        out.print("Locator:" + Fielname[1]);
        String pathReal = getServletContext().getRealPath("\\uploads\\");
        request.setAttribute("Description", Fielname[0]);
        request.setAttribute("Locator", Fielname[1]);
        request.setAttribute("path", pathReal);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    } finally {
        out.close();
    }
}