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

上傳的地址:

    @RequestMapping(value = "/uploadImage" )
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()){
            // TODO
        }
        return "uploadImage.html";
    }

解決方法

1. 需要添加一個獲取上傳頁面的方法映射上傳頁。
2. 修改上傳文件的映射地址,如

修改后

HTML:uploadImage.html


    
        
    

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


免責聲明!

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



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