Question

I have a servlet that is used for many different actions, used in the Front Controller pattern. Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"? I can't read the request parameters until I decide this, so I can't dispatch the request to the proper controller.

Any ideas?

Was it helpful?

Solution

Yes, the Content-type header in the user agent's request should include multipart/form-data as described in (at least) the HTML4 spec:

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

OTHER TIPS

If you are going to try using the request.getContentType() method presented above, be aware that:

  1. request.getContentType() may return null.
  2. request.getContentType() may not be equal to "multipart/form-data", but may just start with it.

With this in mind, the check you should run is :

if (request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
// Multipart logic here
}

You can call a method to get the content type.

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getContentType()

According to http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2, the content type will be "multipart/form-data".

Don't forget that:

  1. request.getContentType() may return null.

  2. request.getContentType() may not be equal to "multipart/form-data", but may just start with it.

So, with all this in mind:

if (request.getContentType() != null && 
    request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) 
{
    << code block >>
} 

ServletFileUpload implements isMultipartContent(). Perhaps you can lift this implementation (as opposed to going through the overhead to create a ServletFileUpload) for your needs.

http://www.docjar.com/html/api/org/apache/commons/fileupload/servlet/ServletFileUpload.java.html

You'll have to read the request parameters in order to determine this, at least on some level. The ServletRequest class has a getContentType method that you'll want to look at.

To expand on awm129's answer - Apache commons' implementation corresponds to this:

if (request != null 
        && request.getContentType() != null 
        && request.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/")) {
    ...
}

You can write it a lot shorter using Apache commons' org.apache.commons.lang3.StringUtils:

if (StringUtils.startsWithIgnoreCase(request.getContentType(), "multipart/")) { 
    ... 
}

https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getParts()

java.util.Collection getParts()

Throws: ServletException - if this request is not of type multipart/form-data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top