简体   繁体   中英

How to get form data in controller when the form that was submitted has the attribute enctype="multipart/form-data"?

I am having some trouble getting form data in my controller when the form in my jsp contains the attribute enctype="multipart/form-data" . The attribute is needed because i am uploading a file. I simplified my code to make it easier to understand but assume I have the following.

My model:

public class EmployeeUpdateForm {
    private String name;
    private ContactInfo info;
    //standard getters and setters
}
public class ContactInfo {
    private String streetName;
    private MultipartFile image;
    //standard getters and setters
}

My controller is

@Controller
public class EmployeeController {

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView showForm() {
        //assume this sends you to updateEmployee.jsp
 
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(@ModelAttribute("EmployeeUpdateForm")EmployeeUpdateForm form ) {
        //here I expect form.getInfo().getStreetName() and form.getInfo().getImage() to return something but they are both null values.
    }
}

updateEmployee.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
    <head>
    </head>
    <body>
        <h3>Update Employee Details</h3>
        <form:form action="submit" method="post" enctype="multipart/form-data" id="EmployeeUpdateForm" modelAttribute="EmployeeUpdateForm">
             <div>
                 Street Name: <form:input path="info.streetName" />
             </div>
             <div>
                 New Image: <form:input type="file" path="info.image"/>
             </div>
        </form:form>
    </body>
</html>

When I submit my form and check the value of form.getInfo().getStreetName() and form.getInfo().getImage() within submit() in my controller, both values are null.

However if I remove method="post" enctype="multipart/form-data" from my form in jsp and also remove <form:input type="file" path="info.image"/> from my jsp and then proceed to submit, if I do form.getyInfo().getStreetName() it returns the value I filled in.

How do I get form data in my controller when the form in my jsp has the attribute method="post" enctype="multipart/form-data"??

A resolver was missing. Adding

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM