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.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveFiles(String uploadDir, List<FileItem> list) {

    List filelist = new ArrayList();

    if (list == null) {
        return filelist;
    }//w  ww. jav a  2  s .  c om

    File dir = new File(uploadDir);
    if (!(dir.isDirectory())) {
        dir.mkdirs();
    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!(item.isFormField())) {
            name = item.getName();
            logger.info("saveFiles name=============" + name);

            if (name == null)
                continue;
            if (name.trim().equals("")) {
                continue;
            }

            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }

            File file = null;
            do {
                name = UUID.randomUUID().toString();
                file = new File(uploadPath + name + extName);
            } while (file.exists());

            File saveFile = new File(uploadPath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[(ss.length - 1)]);

            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:com.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;//from ww  w. j a v  a  2  s.  c  om
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "";
    ///opt/apache-tomcat-7.0.59/webapps/noithat
    //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator;
    filePath = File.separator + File.separator + "opt" + File.separator + File.separator;
    filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps";
    filePath += File.separator + File.separator + "noithat";
    filePath += File.separator + File.separator + "upload" + File.separator + File.separator;
    filePath += "images" + File.separator;

    //filePath = "E:" + File.separator;

    // Verify the content type
    String contentType = request.getContentType();
    System.out.println("contentType=" + contentType);
    if (contentType != null && (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("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);
            System.out.println("fileItems.size()=" + fileItems.size());
            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField() && fi.getFieldName().equals(paramName)) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    int dotPos = fi.getName().lastIndexOf(".");
                    if (dotPos < 0) {
                        fileName += ".jpg";
                    } else {
                        fileName += fi.getName().substring(dotPos);
                    }
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // 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 + "<br>");
                    result = fileName;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;//  w  w  w . ja  v a2 s  . c o  m
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:eu.impact_project.iif.t2.client.Helper.java

/**
 * Extracts all the form input values from a request object. Taverna
 * workflows are read as strings. Other files are converted to Base64
 * strings.//from   w w  w  .j a v  a 2 s  .c o  m
 * 
 * @param request
 *            The request object that will be analyzed
 * @return Map containing all form values and files as strings. The name of
 *         the form is used as the index
 */
public static Map<String, String> parseRequest(HttpServletRequest request) {

    // stores all the strings and encoded files from the html form
    Map<String, String> htmlFormItems = new HashMap<String, String>();
    try {

        // 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 items;
        items = upload.parseRequest(request);

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

            // a normal string field
            if (item.isFormField()) {

                // put the string items into the map
                htmlFormItems.put(item.getFieldName(), item.getString());

                // uploaded workflow file
            } else if (item.getFieldName().startsWith("file_workflow")) {

                htmlFormItems.put(item.getFieldName(), new String(item.get()));

                // uploaded file
            } else {

                // encode the uploaded file to base64
                String currentAttachment = new String(Base64.encode(item.get()));

                // put the encoded attachment into the map
                htmlFormItems.put(item.getFieldName(), currentAttachment);
            }
        }

    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return htmlFormItems;
}

From source file:edu.isi.karma.util.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) {
    // Download the file to the upload file folder

    File destinationDir = new File(destinationDirString);
    logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    // Set the size threshold, above which content will be stored on disk.
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    //Set the temporary directory to store the uploaded files of size above threshold.
    fileItemFactory.setRepository(destinationDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;/* w w  w .j  ava2s  .c  o m*/
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                uploadedFile = new File(destinationDir, item.getName());
                if (item instanceof DiskFileItem) {
                    DiskFileItem t = (DiskFileItem) item;
                    if (!t.getStoreLocation().renameTo(uploadedFile))
                        item.write(uploadedFile);
                } else
                    item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java

private static void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer,
        Consumer<BinaryFile> fileConsumer) {

    try {/* w  w w  .  j av a2  s  .c  o  m*/
        if (fileItem.isFormField()) {
            InputStream stream = fileItem.getInputStream();

            valueConsumer.accept(Streams.asString(stream));
        } else {
            BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(),
                    fileItem.getContentType(), fileItem.getName());

            fileConsumer.accept(binaryFile);
        }
    } catch (IOException ioe) {
        throw new BadRequestException("Invalid body", ioe);
    }
}

From source file:com.dien.upload.server.UploadAction.java

/**
 * Returns the value of a text field present in the FileItem collection. 
 * // www .j  av  a  2  s  . com
 * @param sessionFiles collection of fields sent by the client 
 * @param fieldName field name 
 * @return the string value 
 */
public static String getFormField(Vector<FileItem> sessionFiles, String fieldName) {
    FileItem item = findItemByFieldName(sessionFiles, fieldName);
    return item == null || item.isFormField() == false ? null : item.getString();
}

From source file:com.uniquesoft.uidl.servlet.UploadAction.java

/**
 * Returns the value of a text field present in the FileItem collection. 
 * //from ww  w  . jav  a2  s.  com
 * @param sessionFiles collection of fields sent by the client 
 * @param fieldName field name 
 * @return the string value 
 */
public static String getFormField(List<FileItem> sessionFiles, String fieldName) {
    FileItem item = findItemByFieldName(sessionFiles, fieldName);
    return item == null || item.isFormField() == false ? null : item.getString();
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);/*from  www .j a  v  a2s  .c om*/

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:com.zving.platform.SysInfo.java

public static void uploadDB(HttpServletRequest request, HttpServletResponse response) {
    try {//ww  w  . j a v a2  s.  com
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        ServletFileUpload fu = new ServletFileUpload(fileFactory);
        List fileItems = fu.parseRequest(request);
        fu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!(item.isFormField())) {
                String OldFileName = item.getName();
                System.out.println("Upload DB FileName:" + OldFileName);
                long size = item.getSize();
                if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) {
                    continue;
                }
                OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1);
                String ext = OldFileName.substring(OldFileName.lastIndexOf("."));
                if (!(ext.toLowerCase().equals(".dat"))) {
                    response.sendRedirect("DBUpload.jsp?Error=?dat?");
                    return;
                }
                final String FileName = Config.getContextRealPath() + "WEB-INF/data/backup/DBUpload_"
                        + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
                item.write(new File(FileName));

                LongTimeTask ltt = LongTimeTask.getInstanceByType("Install");
                if (ltt != null) {
                    response.sendRedirect("DBUpload.jsp?Error=??");
                    return;
                }
                SessionListener.forceExit();
                Config.isAllowLogin = false;

                ltt = new LongTimeTask() {
                    public void execute() {
                        DBImport di = new DBImport();
                        di.setTask(this);
                        di.importDB(FileName, "Default");
                        setPercent(100);
                        Config.loadConfig();
                        CronManager.getInstance().init();
                    }
                };
                ltt.setType("Install");
                ltt.setUser(User.getCurrent());
                ltt.start();
                response.sendRedirect("DBUpload.jsp?TaskID=" + ltt.getTaskID());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Config.isAllowLogin = true;
    }
}