我有一个multipart / form-data表单,其中包含文件上传部分和其他字段,如复选框。我想基于复选框中的信息创建一个字符串,用“;”分隔以便将其发送到数据库。
我的UploadServlet如下所示:
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
//doSomething
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
}
else
{
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// Do anotherThing
// Can I create a string from the checkbox inputs here?
}
谢谢!
答案 0 :(得分:0)
对于Apache Commons FileUpload,您提交的多部分表单中的每个HTML元素总会有一个项目。
因此,如果您有多个具有相同名称的复选框,您将获得具有相同字段名称的多个项目。换句话说,对于许多复选框,您会发现许多具有相同字段名称但具有不同值的项目。
答案 1 :(得分:0)
您需要自己收集多个具有相同名称的字段。假设这些复选框的输入字段名称是checkboxName
,这是一个启动示例:
List<String> checkboxValues = new ArrayList<String>();
// ... while looping over all items.
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if ("checkboxName".equals(fieldname)) {
checkboxValues.add(fieldvalue);
}
// ... after looping over all items.
StringBuilder builder = new StringBuilder();
for (String checkboxValue : checkboxValues) {
if (builder.length() > 0) builder.append(";");
builder.append(checkboxValue);
}
String semicolonSeparatedCheckboxValues = builder.toString();
// Save in DB. By the way, why not just using a separate table with a FK?
// Storing multiple values delimited in a single DB column is a bad practice.