Issue
I'm using O'Reilly's multipart form library for Servlets to be able to process file uploading. I found it useful and realiable, but I'm facing an issue I can't solve. It's about multiple-value parameters (For example a multiple select). I'm parsing the parameters like following:
List<Units> unitsParams = new ArrayList<Units>();
while (mp != null && (part = mp.readNextPart()) != null) {
if (part.isFile()) {//Es un fichero.
FilePart filePart = (FilePart) part;
if (filePart.getContentType().equals("image/jpeg")) {
InputStream pis = filePart.getInputStream();
// It's a file, handle it
}
} else if (part.isParam()) { // Es un parametro
// Handle the actual params
String namePar = part.getName();
ParamPart paramPart = (ParamPart) part;
String valorPar = paramPart.getStringValue();
boolean fin = null == valorPar;
if (!fin) {
if (namePar.equals("id")) {
id = valorPar;
} else if (namePar.equals("name")) {
orgName = valorPar;
} else if (namePar.equals("unitSelect")) {
unitsParams.add(valorPar);
}
}
}
For a multiple value parameter, I thought it would iterate (send different parts) as many times as the number of values for the param unitSelect
I was sending, but I can get just one value.
Has anybody used this library and faced this issue? I'm trying to avoid changing the library, since the file upload is working perfectly and it's a pain to change a sigificant part of the code for few servlets.
Any suggestion is welcome.
Thanks.
Solution
I don't use O'Reilly multipart/form-data parser for the reason being that Apache Commons FileUpload is more widely used and still actively maintained, and that since Servlet 3.0 you can even use built-in methods such as getPart()
without need for any 3rd party library.
However, after checking the Javadocs and examples it seems like that you'd better use the MultipartRequest
class instead to collect the parameters. It offers getParameter()
and getParameterValues()
methods.
MultipartRequest multipartRequest = new MultipartRequest(request, saveDirectory);
File file = multipartRequest.getFile("file");
String id = multipartRequest.getParameter("id");
String name = multipartRequest.getParameter("name");
String[] unitSelect = multipartRequest.getParameterValues("unitSelect");
// ...
See also:
Answered By - BalusC