Search code examples
javaformsjspcheckboxmultipart

Multipart/form - Create a string from checkboxes and send to db


I have a multipart/form-data form that contains a file upload section and other fields such as checkboxes. I would like to create a string based on the information from checkboxes, delimitered with ";" in order to send it to the database.

My UploadServlet looks like this:

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?

            }

Thanks!


Solution

  • You need to collect multiple fields with the same name yourself. Assuming that the input field name of those checkboxes is checkboxName, here's a kickoff example:

    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.