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.scooterframework.web.controller.ActionControl.java

/**
 * Returns a map of upload files. In each key/value pair, the key is the 
 * field name in the HTTP form, and the value is a <tt>UploadFile</tt> instance.
 * /*from ww w .j a  v  a  2s .co m*/
 * @return a map of field/upload file (UploadFile) pairs
 * @throws Exception
 */
public static Map<String, UploadFile> getUploadFilesMap() throws Exception {
    Map<String, UploadFile> files = new HashMap<String, UploadFile>();
    List<FileItem> items = prepareFileItems();
    for (FileItem item : items) {
        if (!item.isFormField() && !"".equals(item.getName())) {
            files.put(item.getFieldName(), new UploadFile(item));
        }
    }
    return files;
}

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

/**
 * Return the FileItem corresponding to the file uploaded for a form field.
 * /*from ww w .  j a  v a 2s.  c  o m*/
 * @param formfieldName The name of the form field.
 * @param context Context of the request.
 * @return The corresponding FileItem, or <tt>null</tt> if no file was uploaded for that form field.
 */
public FileItem getFile(String formfieldName, XWikiContext context) {
    LOGGER.debug("Searching file uploaded for field " + formfieldName);

    List<FileItem> fileuploadlist = getFileItems(context);
    if (fileuploadlist == null) {
        return null;
    }

    FileItem fileitem = null;
    for (FileItem item : fileuploadlist) {
        if (formfieldName.equals(item.getFieldName())) {
            fileitem = item;
            LOGGER.debug("Found uploaded file!");
            break;
        }
    }

    return fileitem;
}

From source file:it.lufraproini.cms.servlet.Upload.java

private Map prendiInfo(HttpServletRequest request) throws FileUploadException {
    Map info = new HashMap();
    Map files = new HashMap();

    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        items = upload.parseRequest(request);
        ////from w ww  . ja v a  2 s.co m
        for (FileItem item : items) {
            String name = item.getFieldName();
            //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo
            if (name.startsWith("file_to_upload")) {
                files.put(name, item);
            } else {
                info.put(name, item.getString());
            }
        }
        info.put("files", files);
        return info;
    }
    return null;
}

From source file:it.univaq.servlet.Upload_rist.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map rist = new HashMap();
    //prendo id pubblicazione dalla request

    if (ServletFileUpload.isMultipartContent(request)) {
        Map files = new HashMap();
        int idpubb = Integer.parseInt(request.getParameter("id"));
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*//from w  w w  .  j av a 2s  .c  o  m
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapub")) {
                    rist.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
                //prendo id del file se  stato inserito
                ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                if (!isNull(rs1)) {
                    while (rs1.next()) {
                        rist.put("download", rs1.getInt("id"));
                    }
                }

            }

        }

        rist.put("idpub", idpubb);
        //inserisco dati in tab ristampa
        Database.insertRecord("ristampa", rist);

        return true;
    } else
        return false;
}

From source file:com.aplos.core.listeners.MultipartRequest.java

private void addFormParam(FileItem item) {
    String value;//  w  w  w.  j ava  2s  .  co  m
    if (encoding == null) {
        value = item.getString();
    } else {
        try {
            value = item.getString(encoding);
        } catch (UnsupportedEncodingException e) {
            value = item.getString();
        }
    }
    if (formParams.containsKey(item.getFieldName())) {
        formParams.get(item.getFieldName()).add(value);
    } else {
        List<String> items = new ArrayList<String>();
        items.add(value);
        formParams.put(item.getFieldName(), items);
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w  .j a  va2s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    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();
    }
}

From source file:com.aspectran.web.support.multipart.commons.CommonsMultipartFormDataParser.java

private String getString(FileItem fileItem, String encoding) {
    String value;/*from w  w  w . j a  v  a 2  s.  c  om*/
    if (encoding != null) {
        try {
            value = fileItem.getString(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '"
                    + encoding + "': using platform default");
            value = fileItem.getString();
        }
    } else {
        value = fileItem.getString();
    }
    return value;
}

From source file:com.silverpeas.form.form.XmlSearchForm.java

private FileItem getParameter(List<FileItem> items, String parameterName) {
    for (FileItem item : items) {
        if (parameterName.equals(item.getFieldName())) {
            return item;
        }/*from  w  w w  .  java2  s. com*/
    }
    return null;
}

From source file:com.silverpeas.form.form.XmlSearchForm.java

private List<FileItem> getParameters(List<FileItem> items, String parameterName) {
    List<FileItem> parameters = new ArrayList<FileItem>();
    for (FileItem item : items) {
        if (parameterName.equals(item.getFieldName())) {
            parameters.add(item);/*from   www.  j ava2s  .  c o m*/
        }
    }
    return parameters;
}

From source file:edu.pitt.servlets.processAddMedia.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w ww. j av  a 2  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 {

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(filePath));

            // 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();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // 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);
                        //  out.println("Uploaded Filename: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

            catch (FileUploadException ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}