我希望我的表单可以提交带有其他常用字段的图片,但我发现如果我在表单中选择一张图片,提交就会成功,但如果我没有选择图片,提交会抛出400错误:
Type Status Report
Message Required request part 'profilePicture' is not present
Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Apache Tomcat/8.5.23
查看我的jsp代码:
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<sf:form method="POST" modelAttribute="spitter" enctype="multipart/form-data">
<sf:errors path="*" cssClass="error" element="div"></sf:errors><br/>
<sf:label path="id" cssErrorClass="error">User ID:</sf:label> <sf:input path="id" cssErrorClass="error" /><sf:errors path="id" /> <br />
<sf:label path="firstName" cssErrorClass="error">First Name: </sf:label><sf:input path="firstName" cssErrorClass="error"/><sf:errors path="firstName" cssClass="error" /> <br/>
<sf:label path="lastName" cssErrorClass="error">Last Name: </sf:label><sf:input path="lastName" cssErrorClass="error"/><sf:errors path="lastName" cssClass="error"/> <br/>
<sf:label path="password" cssErrorClass="error">Password: </sf:label><sf:password path="password" cssErrorClass="error"/><sf:errors path="password" cssClass="error"/> <br/>
<br />
<label>Profile Picture</label>
<input type="file" name="profilePicture"
accept="image/jpeg,image/png,image/gif" /><br />
<input type="submit" value="Register" />
</sf:form>
这是我的控制器方法:
@RequestMapping(value="/register", method=RequestMethod.POST)
public String processRegistration(
@RequestPart("profilePicture") byte[] profilePicture,
@Valid Spitter spitter, Errors errors)
{
System.out.println("SpitterController.processRegistration is called first time");
if (errors.hasErrors())
{
System.out.println("find errors");
return "registerForm";
}
System.out.println("SpitterController.processRegistration is called");
System.out.println(spitter.toString());
spitterRespository.saveSpitter(spitter);
return "redirect:/spitter/"+spitter.getId();
}
我不知道如何解决这个问题并且不知道原因,有人可以帮助我吗?