Fileupload in Servlets
by Wolfram Saringer (2010-08-10)
last change: 2010-08-10
Due to a problem with UTF-8 encoded data I recently switched from the old (in my case *very* old) com.oreilly.servlet.MultiPartRequest
to Apache Commons FileUpload. Big mistake.
As often the commons package promises everything and the kitchen sink but in truth simply is not up to the job. In this case
there are several things that annoyed me:
*) The interface to the parsed request data. Why can't I access parameters by name? Why do I have to collect them into a ServletRequest-like
structure myself? I will upload the resulting helper class here soon... in case someone else can't do the obvious: switch
to another library.
*) UTF-8 data does not work. The only position FileUpload accepts an encoding string is via setHeaderEncoding() -- which definitly
does not influence parsing of request data... So every string read from a request field must be converted to UTF-8 by hand:
String value = new String (fileItem.getString().getBytes("iso-8859-1"), "UTF-8");
Today I downloaded a fresh copy of the com.oreilly.servlets package, added the encoding parameter to the constructor call
of MultiPartRequest and it just works. The lesson is: avoid Apache commons wherever possible. Note: please read the licensing
info of the com.oreilly.servlet package, which boils down to the fact that each member of the development team should own
a copy of the corresponding O'Reilly book 'Java Servlet Programming', which is excellent but was not updated quite a while.