问题
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