I am not able to get values from both files and text input in a servlet when my form includes multipart/form-data. I am using the apache.commons.fileuploads for help with th
When using multipart/form-data
, the normal input field values are not available by request.getParameter()
because the standard Servlet API prior to version 3.0 doesn't have builtin facilities to parse them. That's exactly why Apache Commons FileUpload exist. You need to check if FileItem#isFormField()
returns true
and then gather them from the FileItem
.
Right now you're ignoring those values in the code. Admittedly, the FileItem
is a misleading name, if it was me, I'd called it MultipartItem
or just Part
representing a part of a multipart/form-data
body which contains both uploaded fields and normal parameters.
Here's a kickoff example how you should parse a multipart/form-data
request properly:
List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process normal fields here.
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value: " + item.getString());
} else {
// Process here.
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value (file name): " + item.getName());
}
}
Note that you also overlooked a MSIE misbehaviour that it sends the full client side path along the file name. You would like to trim it off from the item.getName()
as per the FileUpload FAQ:
String fileName = item.getName();
if (fileName != null) {
filename = FilenameUtils.getName(filename);
}