今天使用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"; }