HTTP Status 400 - Required request part 'file' is not present
今天使用Spring MVC做一个文件上传的功能,在提交表单的时候出现了如下错误:
之所以出现这个错误,是我没有为如下表单域选择要上传的文件就直接点保存按钮了:
看看JSP代码:
<tr> <td> <fmt:message key="com.studentinfomgt.label.avatar"></fmt:message> </td> <td> <input type="file" name="avatar" accept="image/jpeg,image/png,image/gif"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Save"> </td> </tr>
再看看Spring控制器的代码:
@RequestMapping(value="/addStudentByForm", method=POST) public String addStudentByForm(@RequestPart(value="avatar") byte[] avatar, @Valid Student student, Errors errors) throws Exception { if (errors.hasErrors()) { return "addStudentForm"; }
试了很多方式还是有这个问题,于是我想到了Spring API文档:
原来@RequestPart, @RequestParam注解都有一个可选的boolean参数required, 默认就是true, 瞬间醒悟,把Controller的代码改成这样就解决了错误:
@RequestMapping(value="/addStudentByForm", method=POST) public String addStudentByForm(@RequestPart(value="avatar", required=false) byte[] avatar, @Valid Student student, Errors errors) throws Exception { if (errors.hasErrors()) { return "addStudentForm"; }