![](/img/trans.png)
[英]Get selected image to Controller Class with enctype=“multipart/form-data”?
[英]How to get form data in controller when the form that was submitted has the attribute enctype="multipart/form-data"?
当我的 jsp 中的表单包含属性 enctype="multipart/form-data" 时,我在我的控制器中获取表单数据时遇到了一些麻烦。 需要该属性,因为我正在上传文件。 我简化了我的代码以使其更容易理解,但假设我有以下内容。
我的型号:
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
}
我的控制器是
@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.
}
}
更新员工.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>
当我提交表单并检查控制器中 submit() 中 form.getInfo().getStreetName() 和 form.getInfo().getImage() 的值时,两个值都为空。
但是,如果我从我的 jsp 表单中删除 method="post" enctype="multipart/form-data" 并从我的 jsp 中删除 <form:input type="file" path="info.image"/> 然后继续提交,如果我执行 form.getyInfo().getStreetName() 它返回我填写的值。
当我的 jsp 中的表单具有属性 method="post" enctype="multipart/form-data" 时,如何在我的控制器中获取表单数据?
缺少解析器。 添加
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.