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";
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM