Servlet 3.1 - Multipart async processing

2019-04-09 03:06发布

I am testing Servlet 3.1 API to process multipart requests. I am interested in processing some of the parts synchronously (text fields) and other asyncronously (file fields). At first sight it seems that it is not available in Servlet 3.1 (either totally async through request.getInputStream() in an async context or multipart processing similar to apache-commons-fileupload library).

Is there a way to get this sync/async processing using Servlet 3.1?

Thanks in advance for your time! :)

4条回答
来,给爷笑一个
2楼-- · 2019-04-09 03:13

It is not possible to switch between sync/async, none of the common libraries/APIs support that.

The servlet API added support for upload handling in version 3.0, but it is completely blocking.

The Commons Fileupload library has the streaming API, which you can call in a blocking or an async way, but then you would have to implement it yourself.

You may also use this library, which can be configured to work in blocking mode or in async mode (by implementing the ReadListener interface). If you know that certain requests will only contain text fields or small files then you can configure it based on that.

查看更多
来,给爷笑一个
3楼-- · 2019-04-09 03:19

If you can make sure all text fields come first you should be able to read those first, synchronously, and then the file fields, asynchronously.

Otherwise it's only possible by reading the whole request into memory, synchronously or asynchronously, and then process the text fields directly and submitting the file fields to some thread pool.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-09 03:21

I've been searching for a similar example and I'm surprised that after a year since the original question was posted there aren't many.

Anyway, I was about to write my own but my higher judgment kicked in and Google came to the rescue. The Grizzly project have written an asynchronous multi-part example here: https://grizzly.java.net/httpserverframeworkextras.html

This can't be plugged straight into a Servlet 3.1 readListener but I think it should be fairly straight forward to adapt it (my next task).

查看更多
ら.Afraid
5楼-- · 2019-04-09 03:31

Synchronoss Technologies recently open sourced a non-blocking HTTP multipart parser which can be used with Servlet 3.1 here.

You just write your Servlet 3.1 ReadListener, to pass incoming bytes to the NioMultipartParser. The parser will make callbacks to your code for each of the parts received.

Disclaimer: I work for Synchronoss Technologies. We open sourced this because it was quite a headache to implement! There seems to be a gap in functionality provided by Servlet 3.1, so hopefully others will find this library useful.

查看更多
登录 后发表回答