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:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java

/**
 * Parse the multipart request. Store the info about the request parameters
 * and the uploaded files./*  ww  w.j a  v  a 2  s.co m*/
 */
public MultipartHttpServletRequest(HttpServletRequest request, int maxFileSize) throws IOException {
    super(request);

    Map<String, List<String>> parameters = new HashMap<String, List<String>>();
    Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();

    File tempDir = figureTemporaryDirectory(request);
    ServletFileUpload upload = createUploadHandler(maxFileSize, tempDir);

    parseQueryString(request.getQueryString(), parameters);

    try {
        List<FileItem> items = parseRequestIntoFileItems(request, upload);

        for (FileItem item : items) {
            // Process a regular form field
            if (item.isFormField()) {
                addToParameters(parameters, item.getFieldName(), item.getString("UTF-8"));
                log.debug("Form field (parameter) " + item.getFieldName() + "=" + item.getString());
            } else {
                addToFileItems(files, item);
                log.debug("File " + item.getFieldName() + ": " + item.getName());
            }
        }
    } catch (FileUploadException e) {
        fileUploadException = e;
        request.setAttribute(FileUploadServletRequest.FILE_UPLOAD_EXCEPTION, e);
    }

    this.parameters = Collections.unmodifiableMap(parameters);
    log.debug("Parameters are: " + this.parameters);
    this.files = Collections.unmodifiableMap(files);
    log.debug("Files are: " + this.files);
    request.setAttribute(FILE_ITEM_MAP, this.files);
}

From source file:admin.controller.ServletChangeLooks.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods.//from www  .  j  a  va 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
  */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = "";
    String fileName, fieldName, uploadPath, deletePath, file_name_to_delete = "", uploadPath1;
    Looks look;
    RequestDispatcher request_dispatcher;
    String lookname = "", lookid = "";
    Integer organization = 0;
    look = new Looks();
    boolean check = false;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        // Verify the content type
        String contentType = request.getContentType();
        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(AppConstants.TMP_FOLDER));

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

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

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("lookname")) {
                        lookname = fi.getString();
                    }
                    if (fieldName.equals("lookid")) {
                        lookid = fi.getString();
                    }
                    if (fieldName.equals("organization")) {
                        organization = Integer.parseInt(fi.getString());
                    }
                    file_name_to_delete = look.getFileName(Integer.parseInt(lookid));
                } else {

                    check = look.checkAvailabilities(Integer.parseInt(lookid), lookname, organization);

                    if (check == false) {

                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(AppConstants.LOOK_IMAGES_HOME);

                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = lookname + "_" + Str + ".png";
                        fileName = lookname + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = AppConstants.LOOK_IMAGES_HOME + File.separator + fileName;
                        String delete_path = AppConstants.LOOK_IMAGES_HOME + File.separator
                                + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                        look.changeLooks(Integer.parseInt(lookid), lookname, fileName, organization);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/editlook.jsp?exist=exist&look_id=" + lookid
                                        + "&look_name=" + lookname + "&organization_id=" + organization
                                        + "&image_file_name=" + file_name_to_delete);
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing the looks", ex);
    } finally {
        out.close();
    }

}

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

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

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

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

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

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

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

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

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

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config,
        Validator validator) {//from w  w  w. j  ava 2  s.  co  m

    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);
    uploader.setSizeMax(config.getSizeLimit());
    uploader.setFileSizeMax(config.getFileSizeLimit());

    try {
        final List<FileItem> items = uploader.parseRequest(request);
        logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size());

        for (FileItem item : items) {
            String name = item.getFieldName();
            name = fixIndexedParameters(name, indexes);

            if (item.isFormField()) {
                logger.debug("{} is a field", name);
                params.put(name, getValue(item, request));

            } else if (isNotEmpty(item)) {
                logger.debug("{} is a file", name);
                processFile(item, name, request);

            } else {
                logger.debug("A file field is empty: {}", item.getFieldName());
            }
        }

        for (String paramName : params.keySet()) {
            Collection<String> paramValues = params.get(paramName);
            request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
        }

    } catch (final SizeLimitExceededException e) {
        reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
        reportFileUploadException(e, validator);
    }
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/asyncUpload2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody/*www  .j a va2 s .c  o  m*/
public ResponseEntity<String> asyncFileUpload2(HttpServletRequest request) throws Exception {
    MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
    if (request instanceof MultipartHttpServletRequest) {
        CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("fileUpload");
        List<MultipartFile> fs = (List<MultipartFile>) mpr.getFiles("fileUpload");
        System.out.println("f: " + f);

        for (String key : mpr.getParameterMap().keySet()) {
            System.out.println("Param Key: " + key + "\n Value: " + mpr.getParameterMap().get(key));
        }

        for (String key : mpr.getMultiFileMap().keySet()) {
            System.out.println("xParam Key: " + key + "\n xValue: " + mpr.getMultiFileMap().get(key));
        }

    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    Map<String, Object> parameterMap = new HashMap<>();
    Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");

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

    if (ServletFileUpload.isMultipartContent(request)) {
        Map<String, Object> map = new HashMap<>();
        List<FileItem> filefields = new ArrayList<>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) { //contentType: "image/jpeg", isFormField: false, fileName: "Chrysanthemum.jpg"
            if (item.isFormField()) {
                formfields.put(item.getFieldName(), item.getString());
            } else {
                filefields.add(item);
            }
        }

        parameterMap.put("filefields", filefields);
    }

    return new ResponseEntity<>("success", HttpStatus.OK);
}

From source file:com.tc.webshell.servlets.Upload.java

/**
  * Processes requests for both HTTP/*  w w w.j av a2  s.  c o  m*/
  * <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
  */

@SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    res.setContentType("application/json");

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    upload.setFileSizeMax(60000000);

    // Parse the request
    try {
        Database db = ContextInfo.getUserDatabase();

        for (FileItem item : (List<FileItem>) upload.parseRequest(req)) {
            if (!item.isFormField()) {

                InputStream in = item.getInputStream();

                File file = this.createTempFile("upload", item.getName());

                OutputStream fout = new FileOutputStream(file);

                try {
                    byte[] bytes = IOUtils.toByteArray(in);

                    IOUtils.write(bytes, fout);

                    Map<String, String> queryMap = XSPUtils.getQueryMap(req.getQueryString());

                    Document doc = null;

                    if (queryMap.containsKey("documentId")) {
                        doc = new DocFactory().attachToDocument(db, queryMap.get("documentId"), file);
                    } else {
                        doc = new DocFactory().buildDocument(req, db, file);
                    }

                    doc.save();

                    Prompt prompt = new Prompt();

                    prompt.setMessage("file uploaded successfully");

                    prompt.setTitle("info");

                    prompt.addProperty("noteId", doc.getNoteID());

                    prompt.addProperty("unid", doc.getUniversalID());

                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z");

                    String strdate = formatter.format(doc.getCreated().toJavaDate());

                    prompt.addProperty("created", strdate);

                    Vector<Item> items = doc.getItems();
                    for (Item notesItem : items) {
                        prompt.addProperty(notesItem.getName(), notesItem.getText());
                    }

                    String json = MapperFactory.mapper().writeValueAsString(prompt);

                    this.compressResponse(req, res, json);

                    doc.recycle();

                } finally {
                    in.close();

                    if (fout != null) {
                        fout.close();
                        file.delete();//make sure we cleanup
                    }
                }
            } else {
                //
            }
            break;

        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    } finally {
        res.getOutputStream().close();

    }

}

From source file:com.app.framework.web.MultipartFilter.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./*  w ww. j ava 2 s  .c o m*/
 *
 * @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.
 */
@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.
        // Wrap the request with the parameter map which we just created and return it.
        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:edu.purdue.pivot.skwiki.server.ImageUploaderServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {

    connection = null;/*w  ww.  ja v  a2s.com*/
    Statement st = null;

    /* read database details from file */
    BufferedReader br;
    current_project_name = "";
    main_database_name = "";

    try {
        br = new BufferedReader(new FileReader(this.getServletContext().getRealPath("/serverConfig.txt")));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            String first = line.substring(0, line.lastIndexOf(':'));
            String last = line.substring(line.lastIndexOf(':') + 1);

            if (first.contains("content_database")) {
                current_project_name = last;
            }

            if (first.contains("owner_database")) {
                main_database_name = last;
            }

            if (first.contains("username")) {
                postgres_name = last;
            }

            if (first.contains("password")) {
                postgres_password = last;
            }

            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }

        //String everything = sb.toString();
        //System.out.println("file: "+everything);
        br.close();

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/" + current_project_name,
                "postgres", "fujiko");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            cont++;
            try {
                String uuid = UUID.randomUUID().toString();
                String saveName = uuid + '.' + FilenameUtils.getExtension(item.getName());

                //               String saveName = item.getName();

                //write to database
                File file = new File(saveName);
                item.write(file);

                // / Save a list with the received files
                receivedFiles.put(item.getFieldName(), file);
                receivedContentTypes.put(item.getFieldName(), item.getContentType());
                receivedFilePaths.put(item.getFieldName(), file.getAbsolutePath());

                // / Send a customized message to the client.
                response += "File saved as " + file.getAbsolutePath();

                //write filename to database

                String selectStr = "insert into images values (" + "\'" + item.getFieldName() + "\'," + "\'"
                        + file.getAbsolutePath() + "\'" + ")";
                st = connection.createStatement();
                int textReturnCode = st.executeUpdate(selectStr);

            } catch (Exception e) {
                throw new UploadActionException(e.getMessage());
            }
        }
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
}

From source file:com.krawler.spring.hrms.common.hrmsExtApplDocsDAOImpl.java

public void parseRequest(List fileItems, HashMap<String, String> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload) throws ServiceException {

    FileItem fi1 = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();/*from   w  ww  .java 2s  .  c  o  m*/
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            if (fi1.getSize() != 0) {
                fi.add(fi1);
                fileUpload = true;
            }
        }
    }
}

From source file:com.ms.commons.summer.web.multipart.CommonsMultipartEngancedResolver.java

@SuppressWarnings("all")
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
    Map<String, Object> multipartFiles = new HashMap<String, Object>();
    Map<String, Object> multipartParameters = new HashMap<String, Object>();

    for (Iterator<FileItem> it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = it.next();
        if (fileItem.isFormField()) {
            String value = null;//from   ww  w  . jav  a 2s  .c om
            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 {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            if (multipartFiles.containsKey(file.getName())) {
                Object value = multipartFiles.get(file.getName());
                if (value instanceof CommonsMultipartFile) {
                    List<CommonsMultipartFile> fileList = new ArrayList<CommonsMultipartFile>();
                    fileList.add((CommonsMultipartFile) value);
                    fileList.add(file);
                    multipartFiles.put(file.getName(), fileList);
                } else {
                    ((List<CommonsMultipartFile>) value).add(file); //
                    // multipartFiles.put(file.getName(), value);
                }
            } else {
                multipartFiles.put(file.getName(), file);
            }

        }
    }
    for (Map.Entry<String, Object> entry : multipartFiles.entrySet()) {
        Object value = entry.getValue();
        if (value instanceof List) {
            List<CommonsMultipartFile> fileList = (List<CommonsMultipartFile>) value;
            multipartFiles.put(entry.getKey(), fileList.toArray(new CommonsMultipartFile[] {}));
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters);
}