2

How do I recognize in a servlet whether the request sent using HTML form has enctype multipart/form-data or the default application/x-www-form-urlencoded?

Alternatively: is there any other way to recognize which form was used? request.getParameter("some_param") works only with default encoding.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
yosh
  • 3,245
  • 7
  • 55
  • 84
  • Just use `request.getPart("some_param")` or Apache Commons FileUpload. See also [How to upload files in JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824) Don't try to parse it yourself, for sure not if you're already asking trivial questions like this. – BalusC May 31 '12 at 14:21
  • @BalusC It's better to ask than write something really wrong... I'm using Apache Commons FileUpload for multipart, but wasn't sure how to switch between handling multipart and default forms. – yosh May 31 '12 at 14:31

2 Answers2

1

You can identify using Content-Type: header

if(HttpServletRequest.getContentType().contains("form-data")){
   //handle multipart data
 ....
} else if(HttpServletRequest.getContentType().contains("x-www-form-urlencoded")){
   //handle from data
 ....
}

If the web container supports Servlet 3.0, the use HttpServletRequest.getParts() API.

if(request.getParts() !=null){
  //handle multipart
} else {
  //handle form data
}
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
1

I'm using Apache Commons FileUpload for multipart, but wasn't sure how to switch between handling multipart and default forms

Use Apache Commons FileUpload's own ServletFileUpload#isMultipartContent() to check it.

if (ServletFileUpload.isMultipartContent(request)) {
    // Parse with FileUpload.
}
else {
    // Use normal getParameter().
}

See also:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555