Example usage for org.apache.commons.fileupload MultipartStream discardBodyData

List of usage examples for org.apache.commons.fileupload MultipartStream discardBodyData

Introduction

In this page you can find the example usage for org.apache.commons.fileupload MultipartStream discardBodyData.

Prototype

public int discardBodyData() throws MalformedStreamException, IOException 

Source Link

Document

Reads body-data from the current encapsulation and discards it.

Usage

From source file:io.selendroid.testapp.webdrivertestserver.handler.UploadFileHandler.java

public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control)
        throws Exception {
    response.header("Content-Type", "text/html; charset=" + Charsets.UTF_8.name());

    String contentTypeHeader = request.header("Content-Type");
    Map<String, String> contentTypeHeaderFields = extractFields(contentTypeHeader);

    ByteArrayInputStream input = new ByteArrayInputStream(request.bodyAsBytes());
    MultipartStream multipartStream = new MultipartStream(input,
            contentTypeHeaderFields.get("boundary").getBytes());

    boolean hasNext = multipartStream.skipPreamble();
    while (hasNext) {
        Map<String, String> allHeaders = splitHeaders(multipartStream.readHeaders());
        String inputFieldName = extractFields(allHeaders.get("Content-Disposition")).get("name");
        if (UPLOAD_NAMES.contains(inputFieldName)) {
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            multipartStream.readBodyData(data);
            response.content(data.toByteArray());
        } else {/*from w  w  w.j a va2  s  .  c  o  m*/
            multipartStream.discardBodyData();
        }

        hasNext = multipartStream.readBoundary();
    }

    response.content("<script>window.top.window.onUploadDone();</script>").end();
}

From source file:net.unicon.warlock.portlet.RequestReader.java

private static Map readMultipartContent(ActionRequest req) throws WarlockException {

    // Assertions.
    if (req == null) {
        String msg = "Argument 'req' cannot be null.";
        throw new IllegalArgumentException(msg);
    }// w  ww.  ja v a  2  s.  c  om

    Map rslt = new HashMap();

    try {

        // Read the boundry marker.
        int index = req.getContentType().indexOf("boundary=");
        if (index < 0) {
            String msg = "Unable to locate multipart boundry.";
            throw new WarlockException(msg);
        }
        byte[] boundary = req.getContentType().substring(index + 9).getBytes();

        // Read the InputStream.
        InputStream input = req.getPortletInputStream();
        MultipartStream multi = new MultipartStream(input, boundary);
        multi.setHeaderEncoding(req.getCharacterEncoding()); // ...necessary?
        boolean hasMoreParts = multi.skipPreamble();
        while (hasMoreParts) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);
            if (fieldName != null) {
                String subContentType = (String) headers.get("Content-type".toLowerCase());
                if (subContentType != null && subContentType.startsWith("multipart/mixed")) {

                    throw new UnsupportedOperationException("Multiple-file request fields not supported.");

                    /* let's see if we need this...
                                            // Multiple files.
                                            byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9).getBytes();
                                            multi.setBoundary(subBoundary);
                                            boolean nextSubPart = multi.skipPreamble();
                                            while (nextSubPart) {
                    headers = parseHeaders(multi.readHeaders());
                    if (getFileName(headers) != null) {
                        FileItem item = createItem(headers, false);
                        OutputStream os = item.getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        rslt.add(item.getFieldName(), item.getInputStream());
                    } else {
                        // Ignore anything but files inside
                        // multipart/mixed.
                        multi.discardBodyData();
                    }
                    nextSubPart = multi.readBoundary();
                                            }
                                            multi.setBoundary(boundary);
                    */
                } else {
                    if (getFileName(headers) != null) {
                        // A single file.
                        FileItem item = fac.createItem(getFieldName(headers),
                                (String) headers.get("Content-type".toLowerCase()), false,
                                getFileName(headers));
                        OutputStream os = item.getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        String path = item.getName().replace('\\', '/');
                        String[] tokens = path.split("/");
                        FileUpload fu = new FileUpload(tokens[tokens.length - 1], item.getSize(),
                                item.getInputStream(), item.getContentType());
                        rslt.put(item.getFieldName(), new FileUpload[] { fu });
                    } else {
                        // A form field.
                        FileItem item = fac.createItem(getFieldName(headers),
                                (String) headers.get("Content-type".toLowerCase()), true, null);
                        OutputStream os = item.getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        List newEntry = new ArrayList();
                        if (rslt.get(item.getFieldName()) != null) {
                            String[] oldEntry = (String[]) rslt.get(item.getFieldName());
                            newEntry.addAll(Arrays.asList(oldEntry));
                        }
                        newEntry.add(item.getString());
                        rslt.put(item.getFieldName(), newEntry.toArray(new String[0]));
                    }
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }
            hasMoreParts = multi.readBoundary();
        }
    } catch (Throwable t) {
        String msg = "Unable to process multipart form data.";
        throw new WarlockException(msg, t);
    }

    return rslt;

}

From source file:org.sapia.soto.state.cocoon.util.CocoonFileUploadBase.java

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867 </a>
 * compliant <code>multipart/form-data</code> stream. If files are stored on
 * disk, the path is given by <code>getRepository()</code>.
 * //  ww  w. j a  v  a 2s . co  m
 * @param req
 *          The servlet request to be parsed.
 * 
 * @return A list of <code>FileItem</code> instances parsed from the
 *         request, in the order that they were transmitted.
 * 
 * @exception FileUploadException
 *              if there are problems reading/parsing the request or storing
 *              files.
 */
public List /* FileItem */ parseRequest(HttpRequest req) throws FileUploadException {
    if (null == req) {
        throw new NullPointerException("req parameter");
    }

    ArrayList items = new ArrayList();
    String contentType = req.getHeader(CONTENT_TYPE);

    if ((null == contentType) || (!contentType.startsWith(MULTIPART))) {
        throw new InvalidContentTypeException("the request doesn't contain a " + MULTIPART_FORM_DATA + " or "
                + MULTIPART_MIXED + " stream, content type header is " + contentType);
    }

    int requestSize = req.getContentLength();

    if (requestSize == -1) {
        throw new UnknownSizeException("the request was rejected because it's size is unknown");
    }

    if ((sizeMax >= 0) && (requestSize > sizeMax)) {
        throw new SizeLimitExceededException(
                "the request was rejected because " + "it's size exceeds allowed range");
    }

    try {
        int boundaryIndex = contentType.indexOf("boundary=");

        if (boundaryIndex < 0) {
            throw new FileUploadException(
                    "the request was rejected because " + "no multipart boundary was found");
        }

        byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes();

        InputStream input = req.getInputStream();

        MultipartStream multi = new MultipartStream(input, boundary);
        multi.setHeaderEncoding(headerEncoding);

        boolean nextPart = multi.skipPreamble();

        while (nextPart) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);

            if (fieldName != null) {
                String subContentType = getHeader(headers, CONTENT_TYPE);

                if ((subContentType != null) && subContentType.startsWith(MULTIPART_MIXED)) {
                    // Multiple files.
                    byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9)
                            .getBytes();
                    multi.setBoundary(subBoundary);

                    boolean nextSubPart = multi.skipPreamble();

                    while (nextSubPart) {
                        headers = parseHeaders(multi.readHeaders());

                        if (getFileName(headers) != null) {
                            FileItem item = createItem(headers, false);
                            OutputStream os = item.getOutputStream();

                            try {
                                multi.readBodyData(os);
                            } finally {
                                os.close();
                            }

                            items.add(item);
                        } else {
                            // Ignore anything but files inside
                            // multipart/mixed.
                            multi.discardBodyData();
                        }

                        nextSubPart = multi.readBoundary();
                    }

                    multi.setBoundary(boundary);
                } else {
                    FileItem item = createItem(headers, getFileName(headers) == null);
                    OutputStream os = item.getOutputStream();

                    try {
                        multi.readBodyData(os);
                    } finally {
                        os.close();
                    }

                    items.add(item);
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }

            nextPart = multi.readBoundary();
        }
    } catch (IOException e) {
        throw new FileUploadException(
                "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage());
    }

    return items;
}

From source file:uk.ac.cam.arb33.multipartformdecoder.Main.java

public static void main(String[] args) throws IOException {

    if (args.length == 0) {
        printUsage();/* w  w w  . jav a2 s .  c  om*/
        return;
    }

    int outputFileIndex = 1;
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[0]));
    byte[] boundary = getBoundary(in);
    MultipartStream multipartStream = new MultipartStream(in, boundary, 8192, null);
    boolean nextPart = multipartStream.skipPreamble();

    while (nextPart) {

        String header = multipartStream.readHeaders();
        Map<String, String> keyValuePairs = parseHeader(header);
        System.out.println(keyValuePairs.get("Content-Disposition"));

        if (keyValuePairs.containsKey("Content-Disposition")
                && keyValuePairs.get("Content-Disposition").contains("filename=\"")) {
            if (outputFileIndex < args.length) {
                System.out.println(" -> Saving data to " + args[outputFileIndex]);
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(args[outputFileIndex]));
                multipartStream.readBodyData(out);
                outputFileIndex++;
            } else {
                System.out.println(" -> Cannot save file data: insufficent input files specified.");
                multipartStream.discardBodyData();
            }
        } else {
            ByteArrayOutputStream out = (new ByteArrayOutputStream());
            multipartStream.readBodyData(out);
            System.out.println(" -> " + new String(out.toByteArray()));
        }
        nextPart = multipartStream.readBoundary();
    }
}