Felipe Queiroz
Felipe Queiroz

Reputation: 461

multipart/form parameter is coming null

I'm trying to get the request parameters that are sent by a form enctype "multipart/form-data". I am using apache commons fileupload.

My code is below.

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(req);
Iterator uploadIterator = items.iterator();

while(uploadIterator.hasNext()){
FileItem uploadedItem = (FileItem) uploadIterator.next();


if (uploadedItem.isFormField()){

  if (uploadedItem.getFieldName().equals("name")){
    name = uploadedItem.getString();
  }
}else{
  //Uploaded files comes here
}

The HTML code of the form is:

<form name="form" id="form" method="post" action="ServletIncluirEvento"
    enctype="multipart/form-data">
... //Here comes a lot of inputs (I changed the name of the attribute because I am from Brazil and the names are in portuguese)

<select size="9" id="idOpcoesSelecionadas" name="opcoesSelecionadas" multiple style="width: 100%;">
                                            <%  
 it =  colecaoUsuarioSelecionado.iterator();                             String name= "";
 while (it.hasNext()) {
 usuario = (Usuario) it.next();
 name += usuario.getName() + "/"; %>
 <option value="<%=usuario.getLogin()%>">
    <%=usuario.getName()%>
 </option>
<%
  }
%></select>

<input type="hidden" value="<%=name%>" name="name" />

Even so the parameter is coming null.

Someone knows how to solve?

Thank you in advance

Upvotes: 1

Views: 3588

Answers (2)

Felipe Queiroz
Felipe Queiroz

Reputation: 461

To resolve the problem, I redid the jsp page with a tag form enctype "multipart/form-data" for the images that I must upload and, for the other data, a normal form, wich I can get the request parameters normally.

I also did a refactoring to improve the logic.

Thanks for everyone for the tips.

Upvotes: 0

kapandron
kapandron

Reputation: 3671

Modify calling the method equals:

"name".equals(uploadedItem.getFieldName());

And generally speaking I would rewrite your code more clearly:

FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(req);
for (FileItem uploadedItem : items) {
    if (uploadedItem.isFormField()) {
        String fieldName = uploadedItem.getFieldName();

        if ("name".equals(fieldName)){
           name = uploadedItem.getString();
        }
    } else {
        // process file field
    }    
}

This allows to the code become a more comprehensible. It makes no sense to call twice method getFieldName(). And use Generic. It add stability to your code by making check types at compile time. There's no need for casting in the time getting current object.

Upvotes: 4

Related Questions