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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void showFileFieldParameter(FileItem item) {
    if (logger.isDebugEnabled()) {
        logger.debug("[param] {}:{name={}, size={}}", item.getFieldName(), item.getName(), item.getSize());
    }//from  w ww  . ja  va 2s  .  c  o  m
}

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void addFileParameter(FileItem item) {
    final MultipartFormFile formFile = newActionMultipartFormFile(item);
    elementsFile.put(item.getFieldName(), formFile);
    elementsAll.put(item.getFieldName(), formFile);
}

From source file:com.openkm.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*  w w w  .j a  va 2  s .c om*/
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_description")) {
                        mt.setDescription(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_search")) {
                        mt.setSearch(true);
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");

                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java

/**
 * Retrieves the list of FileItem names. {@link #loadFileList(XWikiContext)} needs to be called beforehand.
 * //w w  w. j  a  v a  2  s  .  co  m
 * @param context Context of the request
 * @return List of strings of the item names
 */
public List<String> getFileItemNames(XWikiContext context) {
    List<String> itemnames = new ArrayList<String>();
    List<FileItem> fileuploadlist = getFileItems(context);
    if (fileuploadlist == null) {
        return itemnames;
    }

    for (FileItem item : fileuploadlist) {
        itemnames.add(item.getFieldName());
    }

    return itemnames;
}

From source file:ReceiveImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www.  j  a v a2  s. c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println(isMultipart = ServletFileUpload.isMultipartContent(request));

    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:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            System.out.println(fi.isFormField());
            if (fi.isFormField()) {
                System.out.println("Got a form field: " + fi.getFieldName() + " " + fi);
            } else {
                // Get the uploaded file parameters
                //System.out.println(fi.getString("Command"));

                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();

                System.out.println(fieldName);
                System.out.println(fileName);
                String courseHour, course, regNo, date, temp = fileName;
                int j = temp.indexOf("sep");

                courseHour = temp.substring(0, j);
                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                course = temp.substring(0, j);

                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                regNo = temp.substring(0, j);

                date = temp.substring(j + 3);
                date = date.replaceAll("s", "-");

                System.out.println("ualal" + courseHour + course + regNo + date);

                System.out.println(contentType);

                long sizeInBytes = fi.getSize();
                // Write the file

                String uploadFolder = getServletContext().getRealPath("") + "Photo\\" + course + "\\" + regNo
                        + "\\";
                //                    String uploadFolder =  "\\SUST_PHOTO_PRESENT\\Photo\\" + course + "\\" + regNo + "\\";

                uploadFolder = uploadFolder.replace("\\build", "");
                Path path = Paths.get(uploadFolder);
                //if directory exists?
                if (!Files.exists(path)) {
                    try {
                        Files.createDirectories(path);
                    } catch (IOException e) {
                        //fail to create directory
                        e.printStackTrace();
                    }
                }
                //uploadFolder+= "\\"+date+".jpg";   
                System.out.println(fileName);
                System.out.println(uploadFolder);

                //               
                file = new File(uploadFolder + date);

                date = date.replaceAll("-", "/");
                date = date.substring(0, 10);

                String total_url = uploadFolder + date.replaceAll("/", "-") + ".jpg";
                System.out.println(total_url);

                String formattedUrl = total_url.replaceAll("\\\\", "/");

                System.out.println(formattedUrl.substring(38));

                System.out.println("-------------->>>>>>>>" + course + "  " + date + regNo + total_url);

                AddUser.updateUrl(courseHour, course, date, regNo, formattedUrl.substring(38));
                fi.write(file);

                //                    System.out.println("-------------->>>>>>>>" +course+"  "+ date+ regNo+total_url);
                //                   try {
                //            SavePhoto.saveIMG("CSE", "2016", "tada","F:\\1.png");
                //        } catch (IOException ex) {
                //            Logger.getLogger(SavePhoto.class.getName()).log(Level.SEVERE, null, ex);
                //        }
                System.out.println(uploadFolder);
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.baobao121.baby.common.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /* w  w  w . ja va  2 s.  c om*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:cust_photo_upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w  .  j  a  v a2  s . c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();

    try (PrintWriter out = response.getWriter()) {

        Login ln = (Login) hs.getAttribute("user");

        String pname = ln.getUName();
        String p = "";

        //             
        // creates FileItem instances which keep their content in a temporary file on disk
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //get the list of all fields from request
        List<FileItem> fields = upload.parseRequest(request);
        // iterates the object of list
        Iterator<FileItem> it = fields.iterator();
        //getting objects one by one
        while (it.hasNext()) {
            //assigning coming object if list to object of FileItem
            FileItem fileItem = it.next();
            //check whether field is form field or not
            boolean isFormField = fileItem.isFormField();

            if (isFormField) {
                //get the filed name 
                String fieldName = fileItem.getFieldName();

            } else {

                String extension;
                String fieldName = fileItem.getFieldName();

                if (fieldName.equals("photo"))
                    ;

                {
                    //getting name of file
                    p = new File(fileItem.getName()).getName();
                    //get the extension of file by diving name into substring
                    extension = p.substring(p.indexOf(".") + 1, p.length());
                    ;
                    //rename file...concate name and extension
                    p = pname + "." + extension;

                    try {
                        String filePath = this.getServletContext().getRealPath("/images") + "\\";
                        fileItem.write(new File(filePath + p));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }
                }
            }

        }

        //        hs.setAttribute("photo", photo);
        //        SessionFactory sf=NewHibernateUtil.getSessionFactory();
        //        Session s=sf.openSession();
        //        Transaction t=s.beginTransaction();
        //       Imagedata im=new Imagedata();
        //       im.setIname(pname);
        //       im.setIurl(photo);
        //        s.save(im);
        //        t.commit();
        //          
        RequestDispatcher rd = request.getRequestDispatcher("viewserv");
        rd.forward(request, response);
        //            response.sendRedirect("viewserv");

    } catch (Exception ex) {
        out.println(ex.getMessage());
    }

}

From source file:com.alkacon.opencms.excelimport.CmsResourceExcelImport.java

/**
 * Sets content from uploaded file.<p>
 * //from   w ww  .  j a  v  a 2s  .c  om
 * @param content the parameter value is only necessary for calling this method
 */
public void setParamExcelContent(String content) {

    // use parameter value
    if (content == null) {
        // do nothing   
    }

    // get the file item from the multipart request
    if (getMultiPartFileItems() != null) {
        Iterator i = getMultiPartFileItems().iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getFieldName().equals(PARAM_EXCEL_FILE)) {
                // found the file objectif (fi != null) {
                long size = fi.getSize();
                long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
                // check file size
                if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                    // file size is larger than maximum allowed file size, throw an error
                    //throw new CmsWorkplaceException();
                }
                m_excelContent = fi.get();
                m_excelName = fi.getName();
                fi.delete();
            } else {
                continue;
            }
        }
    }
}

From source file:crds.pub.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*  w w w.j a  v  a2 s . c  o m*/
 *
 */
@SuppressWarnings({ "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id
            + currentFolderStr + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  ww  .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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String type = "";
    CallableStatement pro;

    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);
                        type = new String(b);
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT_TEST(?,?)}");
                pro.setInt(1, 2);
                pro.setString(2, name);
                pro.executeQuery();
                pro.close();
                connect.close();
                if (name != null) {
                    request.setAttribute("type", type);
                    request.setAttribute("success", "ok");
                }
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/SearchEngine.jsp").forward(request, response);
    } finally {
        out.close();
    }
}