Parsing multipart/form-data using Apache Commons File Upload

微笑、不失礼 提交于 2020-01-02 04:55:11

问题


Does Apache Commons File Upload package provides a generic interface to stream parse multipart/form-data chunks via InputStream, appending Array<Byte>, or via any other generic streaming interface?

I know they have a streaming API but the example only shows you how to do that via ServletFileUpload, which I reckon must be specific to Servlet.

If not, are there any other alternative frameworks in JVM that lets you do exactly this? Sadly, the framework that I am using, Spray.io, doesn't seem to provide a way to do this.


回答1:


bayou.io has a generic MultipartParser

You might need some adapters to work with it, since it has its own Async and ByteSource interfaces.

The following example shows how to use the parser synchronously with InputStream

    String msg = ""
        //+ "preamble\r\n"
        +"--boundary\r\n"
        +"Head1: Value1\r\n"
        +"Head2: Value2\r\n"
        +"\r\n"
        +"body.body.body.body."

        +"\r\n--boundary\r\n"
        +"Head1: Value1\r\n"
        +"Head2: Value2\r\n"
        +"\r\n"
        +"body.body.body.body."

        +"\r\n--boundary--"
        + "epilogue";

    InputStream is = new ByteArrayInputStream(msg.getBytes("ISO-8859-1"));
    ByteSource byteSource = new InputStream2ByteSource(is, 1024);
    MultipartParser parser = new MultipartParser(byteSource, "boundary");
    while(true)
    {
        try
        {
            MultipartPart part = parser.getNextPart().sync();   // async -> sync
            System.out.println("== part ==");
            System.out.println(part.headers());
            ByteSource body = part.body();
            InputStream stream = new ByteSource2InputStream(body, Duration.ofSeconds(1));
            drain(stream);
        }
        catch (End end) // control exception from getNextPart()
        {
            System.out.println("== end of parts ==");
            break;
        }
    }


来源:https://stackoverflow.com/questions/30387603/parsing-multipart-form-data-using-apache-commons-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!