Example usage for org.apache.commons.fileupload FileItemStream isFormField

List of usage examples for org.apache.commons.fileupload FileItemStream isFormField

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream isFormField.

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:com.lemania.sis.server.servlet.GcsServlet.java

/**
 * Writes the payload of the incoming post as the contents of a file to GCS.
 * If the request path is /gcs/Foo/Bar this will be interpreted as a request
 * to create a GCS file named Bar in bucket Foo.
 * //w  ww.  j  a  v  a 2s .c om
 * @throws ServletException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    //
    GcsOutputChannel outputChannel = gcsService.createOrReplace(getFileName(req),
            GcsFileOptions.getDefaultInstance());

    ServletFileUpload upload = new ServletFileUpload();
    resp.setContentType("text/plain");
    //
    InputStream fileContent = null;
    FileItemIterator iterator;
    try {
        iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            if (item.isFormField()) {
                //
            } else {
                fileContent = stream;
                break;
            }
        }
    } catch (FileUploadException e) {
        //
        e.printStackTrace();
    }
    //
    copy(fileContent, Channels.newOutputStream(outputChannel));
}

From source file:com.oprisnik.semdroid.SemdroidServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("doPost");
    StringBuilder sb = new StringBuilder();
    try {//ww w .  j  a v a  2s  . co  m
        ServletFileUpload upload = new ServletFileUpload();
        // set max size (-1 for unlimited size)
        upload.setSizeMax(1024 * 1024 * 30); // 30MB
        upload.setHeaderEncoding("UTF-8");

        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                // Process regular form fields
                // String fieldname = item.getFieldName();
                // String fieldvalue = item.getString();
                // log.info("Got form field: " + fieldname + " " + fieldvalue);
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getBaseName(item.getName());
                log.info("Got file: " + filename);
                InputStream filecontent = null;
                try {
                    filecontent = item.openStream();
                    // analyze
                    String txt = analyzeApk(filecontent);
                    if (txt != null) {
                        sb.append(txt);
                    } else {
                        sb.append("Error. Could not analyze ").append(filename);
                    }
                    log.info("Analysis done!");
                } finally {
                    if (filecontent != null) {
                        filecontent.close();
                    }
                }
            }
        }
        response.getWriter().print(sb.toString());
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    } catch (Exception ex) {
        log.warning("Exception: " + ex.getMessage());
        log.throwing(this.getClass().getName(), "doPost", ex);
    }

}

From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java

private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException {
    Task task = null;//w  w  w  . j  a va 2 s.c  o m

    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator iterator = null;
    InputStream itemStream = null;

    try {
        ImageReplicationType replicationType = null;

        iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            itemStream = item.openStream();

            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                switch (fieldName.toUpperCase()) {
                case "IMAGEREPLICATION":
                    replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase());
                    break;
                default:
                    logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName));
                }
            } else {
                if (replicationType == null) {
                    throw new ImageUploadException(
                            "ImageReplicationType is required and should be encoded before image data in the upload request.");
                }

                task = imageFeClient.create(itemStream, item.getName(), replicationType);
            }

            itemStream.close();
            itemStream = null;
        }
    } catch (IllegalArgumentException ex) {
        throw new ImageUploadException("Image upload receives invalid parameter", ex);
    } catch (IOException ex) {
        throw new ImageUploadException("Image upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new ImageUploadException("Image upload FileUploadException", ex);
    } finally {
        flushRequest(iterator, itemStream);
    }

    if (task == null) {
        throw new ImageUploadException("There is no image stream data in the image upload request.");
    }

    return task;
}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;/*from w  w w . j a  va 2  s.co m*/
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {/*from ww w . j av a2 s.c o  m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:is.hax.spring.web.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Parse the request
    try {/*from  ww w  .  ja v a  2 s.  c o m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);

                if (multipartFiles.put(name, file) != null) {
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();

        try {//from www  . j a  v a 2  s.c o  m
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    System.out.println(
                            "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                } else {
                    System.out
                            .println("File field " + name + " with file name " + item.getName() + " detected.");
                    DataSource source = createDataSource(item);
                    SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source);
                }

                JSONObject jsonResponse = null;
                try {
                    jsonResponse = new JSONObject();
                    jsonResponse.put("success", true);
                    jsonResponse.put("error", "Upload successful");
                } catch (Exception e) {

                }

                Writer w = new OutputStreamWriter(response.getOutputStream());
                w.write(jsonResponse.toString());
                w.close();

                stream.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.google.reducisaurus.servlets.BaseServlet.java

private String collectFromFileUpload(final HttpServletRequest req) throws IOException, ServletException {
    StringBuilder collector = new StringBuilder();
    try {//from  w w w.  ja  v  a  2  s  .c om
        ServletFileUpload sfu = new ServletFileUpload();
        FileItemIterator it = sfu.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            if (!item.isFormField()) {
                InputStream stream = item.openStream();
                collector.append(IOUtils.toString(stream, "UTF-8"));
                collector.append("\n");
                IOUtils.closeQuietly(stream);
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    return collector.toString();
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {/*w w w .  j a  v  a 2 s  .  c om*/
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        FileItemStream fileItem = null;
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                fileItem = item;
            }
        }
        if (fileItem != null) {
            args.put("contentType", fileItem.getContentType());
            args.put("fileName", FileUtils.filename(fileItem.getName()));
            System.out.println("uploading args " + args);
            String context = args.get("context");
            String model = args.get("model");
            String xq = args.get("xq");
            System.out.println(context + "," + model + "," + xq);
            File f = new File(args.get("fileName"));
            System.out.println(f.getAbsolutePath());
            /*
             * TODO: pboysen get the state, context and fileManager and store the
             * stream in fileName.  Parameters should be passed to locate state 
             * and conversion options.
             */
            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script>");
            out.println("top.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
        } else {
            //TODO: add error code
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java

@Override
@POST/*from   ww w .j ava 2  s .c o  m*/
@Path("/upload")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String bookId = null;
            String contentType = null;
            // String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }
                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray(); // fileItem.get();
                        size = bytes.length;
                        // data = Base64.encodeBytes(bytes);
                    }
                }
            }

            // Add the logo
            Book book = bookDAO.getBookById(bookId);

            // Update the front cover
            BookCategory cat = holder.getCategoryByName(book.getCategory());
            BookCover cover = holder.getCoverByName(book.getCoverName());
            String authorName = bookDAO.getAuthorName(book.getAuthorId());
            //String frontBookCoverEncoded = imgService
            //      .createDefaultFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes,
                    authorName);

            //String smallFrontBookCoverEncoded = imgService
            //      .createDefaultSmallFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes,
                    authorName);

            // Save it
            // Add the logo
            book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size,
                    frontBookCoverBytes, frontBookCoverSmallBytes);

        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}