gpt4 book ai didi

java - 多部分/表单参数即将为空

转载 作者:行者123 更新时间:2023-11-29 05:56:22 25 4
gpt4 key购买 nike

我正在尝试获取由表单编码类型“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" />

即便如此,参数仍为空。

有人知道怎么解决吗?

提前致谢

最佳答案

修改调用方法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 .它通过在编译时检查类型来增加代码的稳定性。获取当前对象时无需强制转换。

关于java - 多部分/表单参数即将为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com