Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle multipart/form-data POST requests in my java servlet?

I'm having a very hard time dealing with multipart/form-data requests with my java application server. From what I have found out, the servlet 3.0 specification provides methods such as HttpServletRequest.getParts(), which would be ideal for processing the form data uploaded to my servlet.

However, this method is part of the 3.0 servlet specification, and my application server (Tomcat 6) does not support this yet. Even with a valid 3.0 web.xml file and the java EE 6 libs, I get the following exception when trying to call getParts():

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getParts()Ljava/util/Collection;

Switching application servers is not really a feasible option for this project. Are there any third-party libraries available for processing multipart/form-data within java servlets?

like image 268
Nik Reiman Avatar asked Aug 18 '10 09:08

Nik Reiman


People also ask

How do you handle a multipart request in Java?

Class MultipartRequest. A utility class to handle multipart/form-data requests, the kind of requests that support file uploads. This class emulates the interface of HttpServletRequest , making it familiar to use. It uses a "push" model where any incoming files are read and saved directly to disk in the constructor.

How do you post a multipart data?

A multipart formpost is what an HTTP client sends when an HTML form is submitted with enctype set to "multipart/form-data". It is an HTTP POST request sent with the request body specially formatted as a series of "parts", separated with MIME boundaries.


2 Answers

Check out Apache Commons Fileupload. It gives you a programmatic API to parse a multipart request, and iterate through the parts of it individually.

I've used it in the past for straightforward multipart processing and it does the job fine without being overly complicated.

like image 190
Andrzej Doyle Avatar answered Sep 18 '22 22:09

Andrzej Doyle


Tomcat 6 does not and will not support Servlet Specification 3.0. You should attempt doing this on Tomcat 7, but I'm not really sure whether this functionality is present in the beta release that is currently available. The functionality is expected to be present in the production release though.

You could continue using Apache Commons FileUpload like posted in the other answer, or you could use Glassfish (depending on the current phase and type of your project).

like image 36
Vineet Reynolds Avatar answered Sep 17 '22 22:09

Vineet Reynolds