Example usage for org.apache.commons.fileupload FileItemIterator next

List of usage examples for org.apache.commons.fileupload FileItemIterator next

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator next.

Prototype

FileItemStream next() throws FileUploadException, IOException;

Source Link

Document

Returns the next available FileItemStream .

Usage

From source file:kg12.Ex12_2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   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();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_2</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
                InputStream is = item.openStream();

                String fileName = item.getName();
                int len = 0;
                byte[] buffer = new byte[fileSizeMax];

                FileOutputStream fos = new FileOutputStream(
                        "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName);
                try {
                    while ((len = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                } finally {
                    fos.close();
                }

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*from  w  ww  . ja  v  a  2  s.  c om*/

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:com.qualogy.qafe.web.UploadService.java

public String uploadFile(HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload();
    String errorMessage = "";
    byte[] filecontent = null;
    String appUUID = null;//from ww  w .  ja v  a2  s . c o  m
    String windowId = null;
    String filename = null;
    String mimeType = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    try {
        FileItemIterator fileItemIterator = upload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream item = fileItemIterator.next();
            inputStream = item.openStream();
            // Read the file into a byte array.
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len = 0;
            while (-1 != (len = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, len);
            }
            if (filecontent == null) {
                filecontent = outputStream.toByteArray();
                filename = item.getName();
                mimeType = item.getContentType();
            }

            if (item.getFieldName().indexOf(APP_UUID) > -1) {
                appUUID = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1);
            }
            if (item.getFieldName().indexOf(APP_WINDOWID) > -1) {
                windowId = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1);
            }
        }

        if ((appUUID != null) && (windowId != null)) {
            if (filecontent != null) {
                int maxFileSize = 0;
                if (ApplicationCluster.getInstance()
                        .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) {
                    String maxUploadFileSzie = ApplicationCluster.getInstance()
                            .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE);
                    if (StringUtils.isNumeric(maxUploadFileSzie)) {
                        maxFileSize = Integer.parseInt(maxUploadFileSzie);
                    }
                }

                if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) {
                    Map<String, Object> fileData = new HashMap<String, Object>();
                    fileData.put(FILE_MIME_TYPE, mimeType);
                    fileData.put(FILE_NAME, filename);
                    fileData.put(FILE_CONTENT, filecontent);

                    String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString();
                    appUUID = concat(appUUID, windowId);

                    ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData);

                    return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID;
                } else {
                    errorMessage = "The maxmimum filesize in bytes is " + maxFileSize;
                }
            }
        } else {
            errorMessage = "Application UUID not specified";
        }
        inputStream.close();
        outputStream.close();
    } catch (Exception e) {
        errorMessage = e.getMessage();
    }

    return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage;
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from  w  ww . j a va  2  s .c  o m*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

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  .ja  va  2 s .  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:de.mpg.imeji.presentation.upload.UploadBean.java

public void upload() throws Exception {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from ww w.j  a va 2  s  .c  o m*/
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                title = item.getName();
                StringTokenizer st = new StringTokenizer(title, ".");
                while (st.hasMoreTokens()) {
                    format = st.nextToken();
                }
                mimetype = "image/" + format;
                // TODO remove static image description
                description = "";
                try {
                    UserController uc = new UserController(null);
                    User user = uc.retrieve(getUser().getEmail());
                    try {
                        DepositController controller = new DepositController();
                        Item escidocItem = controller.createEscidocItem(stream, title, mimetype, format);
                        controller.createImejiImage(collection, user, escidocItem.getOriginObjid(), title,
                                URI.create(EscidocHelper.getOriginalResolution(escidocItem)),
                                URI.create(EscidocHelper.getThumbnailUrl(escidocItem)),
                                URI.create(EscidocHelper.getWebResolutionUrl(escidocItem)));
                        // controller.createImejiImage(collection, user, "escidoc:123", title,
                        // URI.create("http://imeji.org/test"), URI.create("http://imeji.org/test"),
                        // URI.create("http://imeji.org/test"));
                        sNum += 1;
                        sFiles.add(title);
                    } catch (Exception e) {
                        fNum += 1;
                        fFiles.add(title);
                        logger.error("Error uploading image: ", e);
                        // throw new RuntimeException(e);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        logger.info("Upload finished");
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

/**
 * Tests, whether an {@link InvalidFileNameException} is thrown.
 *///from  ww  w .  j a  v a  2 s .  c  o m
public void testInvalidFileNameException() throws Exception {
    final String fileName = "foo.exe\u0000.png";
    final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\""
            + fileName + "\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n"
            + "This is the content of the file\n" + "\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"field\"\r\n" + "\r\n" + "fieldValue\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value1\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value2\r\n" + "-----1234--\r\n";
    final byte[] reqBytes = request.getBytes("US-ASCII");

    FileItemIterator fileItemIter = parseUpload(reqBytes.length, new ByteArrayInputStream(reqBytes));
    final FileItemStream fileItemStream = fileItemIter.next();
    try {
        fileItemStream.getName();
        fail("Expected exception");
    } catch (InvalidFileNameException e) {
        assertEquals(fileName, e.getName());
        assertTrue(e.getMessage().indexOf(fileName) == -1);
        assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1);
    }

    List<FileItem> fileItems = parseUpload(reqBytes);
    final FileItem fileItem = fileItems.get(0);
    try {
        fileItem.getName();
        fail("Expected exception");
    } catch (InvalidFileNameException e) {
        assertEquals(fileName, e.getName());
        assertTrue(e.getMessage().indexOf(fileName) == -1);
        assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1);
    }
}

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

private String collectFromFileUpload(final HttpServletRequest req) throws IOException, ServletException {
    StringBuilder collector = new StringBuilder();
    try {/*w  w  w  .  j av  a  2s  .c o m*/
        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:freedots.web.MusicXML2BrailleServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Score score = null;/*  w  ww.  j  a  v  a 2  s  .c om*/
    BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille;
    int width = 40, height = 25;
    InputStream stream = null;
    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            final FileItemStream item = iterator.next();
            if (item.getFieldName().compareTo("file.xml") == 0) {
                String extension = "xml";
                if (item.getName().endsWith(".mxl"))
                    extension = "mxl";
                score = parseMusicXML(item.openStream(), extension);
            } else if (item.getFieldName().compareTo("encoding") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null) {
                    try {
                        brailleEncoding = Enum.valueOf(BrailleEncoding.class, line);
                    } catch (IllegalArgumentException e) {
                        LOG.info("Unknown encoding " + line + ", falling back to default");
                    }
                }
            } else if (item.getFieldName().compareTo("width") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null && !line.isEmpty()) {
                    try {
                        final int value = Integer.parseInt(line);
                        if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE)
                            width = value;
                    } catch (NumberFormatException e) {
                        LOG.info("Not a proper number: " + line + ", falling back to default");
                    }
                }
            } else if (item.getFieldName().compareTo("height") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null && !line.isEmpty()) {
                    try {
                        final int value = Integer.parseInt(line);
                        if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE)
                            height = value;
                    } catch (NumberFormatException e) {
                        LOG.info("Not a proper number: " + line + ", falling back to default");
                    }
                }
            }
        }
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        LOG.info("FileUploadException error");
        resp.sendError(500);
    }

    if (score != null) {
        writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp);
    } else {
        resp.sendRedirect("/");
    }
}

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }//from  w w w  .j a  v  a2 s  .c  o m

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}