Library and examples of parsing multipart/form-data from inputstream

Linus picture Linus · Nov 19, 2012 · Viewed 30.6k times · Source

The response to one kind of HTTP request I send is a multipart/form-data looks something like:

--------boundary123
Content-Disposition: form-data; name="json"
Content-Type: application/json

{"some":"json"}
--------boundary123
Content-Disposition: form-data; name="bin"
Content-Type: application/octet-stream

<file data>

--------boundary123

I've been using apache to send and receive the HTTP requests, but I can't seem to find an easy way to use it to parse the above for easy access of the form fields.

I would prefer not to reinvent the wheel, so I'm looking for a library that allows me to do something similar to:

MultipartEntity multipart = new MultipartEntity(inputStream);
InputStream bin = multipart.get("bin");

Any suggestions?

Answer

Linus picture Linus · Nov 21, 2012

Example code using deprecated constructor:

import java.io.ByteArrayInputStream;

import org.apache.commons.fileupload.MultipartStream;

public class MultipartTest {

    // Lines should end with CRLF
    public static final String MULTIPART_BODY =
            "Content-Type: multipart/form-data; boundary=--AaB03x\r\n"
            + "\r\n"
            + "----AaB03x\r\n"
            + "Content-Disposition: form-data; name=\"submit-name\"\r\n"
            + "\r\n"
            + "Larry\r\n"
            + "----AaB03x\r\n"
            + "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"\r\n"
            + "Content-Type: text/plain\r\n"
            + "\r\n"
            + "HELLO WORLD!\r\n"
            + "----AaB03x--\r\n";

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

        byte[] boundary = "--AaB03x".getBytes();

        ByteArrayInputStream content = new ByteArrayInputStream(MULTIPART_BODY.getBytes());

        @SuppressWarnings("deprecation")
        MultipartStream multipartStream =
                new MultipartStream(content, boundary);

        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            String header = multipartStream.readHeaders();
            System.out.println("");
            System.out.println("Headers:");
            System.out.println(header);
            System.out.println("Body:");
            multipartStream.readBodyData(System.out);
            System.out.println("");
            nextPart = multipartStream.readBoundary();
        }
    }
}