Springboot 上傳文件 The current request is not a multipart request 錯誤

錯誤

前端上傳文件,後端方法中 @RequestParam("file") MultipartFile file 方法接收報錯。

原因

刷新頁面的請求地址是:http://localhost:8080/uploadImage,後臺中上傳文件的映射地址(action="/uploadImage")也是 /uploadImage,剛打開上傳頁面 uploadImage.html 刷新時的請求並非是一個 multipart request 請求,沒有 MultipartFile 等參數,故此報錯。

待刷新的頁面:
http://localhost:8080/uploadImage

上傳的地址:

<form enctype="multipart/form-data" action="/uploadImage" method="POST">
    @RequestMapping(value = "/uploadImage" )
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()){
            // TODO
        }
        return "uploadImage.html";
    }

解決方法

1. 需要添加一個獲取上傳頁面的方法映射上傳頁。
2. 修改上傳文件的映射地址,如 <form enctype="multipart/form-data" action="/insertImage" method="POST">

修改後

HTML:uploadImage.html

<form enctype="multipart/form-data" action="/upload" method="POST">
    <div class="form-group">
        <label>文件上傳</label>
        <input type="file" name="fileName" accept="image/*">
    </div>
    <button type="submit" class="btn btn-primary">上傳</button>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <button type="reset" class="btn btn-secondary">重置</button>
</form>

controller:

    /**
     * @Description: 正常訪問 圖像上傳頁面
     * @Date: 2019/11/8 19:05
     * @Params:
     * @ReturnType:
     **/
    @RequestMapping(value = "/uploadImage")
    public String uploadImagePage() {
        return "/uploadImage";
    }


    /**
     * @Description: 上傳圖像
     * @Date: 2019/11/8 19:06
     * @Params:
     * @ReturnType:
     **/
    @RequestMapping(value = "/upload")
    @ResponseBody
    public ModelAndView upload(@RequestParam("fileName") MultipartFile file) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        String uploadRes = "";
        if (Objects.isNull(file) || file.isEmpty() || Strings.isEmpty(file.getOriginalFilename())) {
            modelAndView.setViewName("uploadImage.html");
            return modelAndView;
        }
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

        int size = (int) file.getSize();
        logger.info(String.format("文件[%s] 大小爲[%s]", fileName, size));

        String rootPath = "F://test";
        try {
            // 保存文件
            File dest = new File(rootPath + "/" + fileName);
            file.transferTo(dest);
            uploadRes = "true";
        } catch (Exception e) {
            e.printStackTrace();
            uploadRes = "false";
        }
        modelAndView.addObject("uploadResult", uploadRes);
        modelAndView.setViewName("uploadImage.html");
        return modelAndView;
    }

參考鏈接

https://www.jianshu.com/p/be1af489551c
https://blog.csdn.net/ahwsk/article/details/79707807
https://www.cnblogs.com/luxd/p/9264826.html
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章