0

我有一个 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?

            }

谢谢!

4

2 回答 2

0

对于 Apache Commons FileUpload,您提交的多部分表单中的每个 HTML 元素始终有一个项目。

因此,如果您有多个具有相同名称的复选框,您将获得多个具有相同字段名称的项目。换句话说,对于许多复选框,您会发现许多项具有相同的字段名称,但具有不同的值。

于 2012-06-11T15:50:52.160 回答
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.
于 2012-06-11T16:22:55.627 回答