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