错误
前端上传文件,后端方法中 @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>
<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