multipart / form参数为null

时间:2012-08-14 19:35:08

标签: java jsp servlets apache-commons

我正在尝试获取由表单enctype“multipart / form-data”发送的请求参数。我正在使用apache commons fileupload。

我的代码如下。

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
}

表单的HTML代码为:

<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" />

即使如此,参数也为空。

有人知道如何解决?

提前谢谢

2 个答案:

答案 0 :(得分:3)

修改调用方法equals

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

一般来说,我会更清楚地重写你的代码:

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
    }    
}

这使得代码变得更易于理解。调用两次方法getFieldName()是没有意义的。并使用Generic。它通过在编译时创建检查类型来增加代码的稳定性。获取当前对象时无需进行投射。

答案 1 :(得分:0)

为了解决这个问题,我使用标签格式enctype“multipart / form-data”为我必须上传的图像重新编写jsp页面,对于其他数据,我是一个普通表单,我可以获取请求参数通常

我也进行了重构以改善逻辑。

感谢大家的提示。

相关问题