1. 在springmvc.xml里配置文件解析器
<!--5.配置文件解析器-->
<!-- 此处id为固定写法,不能随便取名-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"></property>
</bean>
2. 编写Web层:CourseController
/*
课程图片上传
*/
@RequestMapping("/courseUpload")
public ResponseResult fileUpload(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException {
//1.判断接收到的上传文件是否为空
if(file.isEmpty()){
throw new RuntimeException();
}
//2.获取项目部署路径
// D:\apache-tomcat-8.5.56\webapps\ssm-web\
String realPath = request.getServletContext().getRealPath("/");
// D:\apache-tomcat-8.5.56\webapps
String substring = realPath.substring(0, realPath.indexOf("ssm-web"));
//3.获取原文件名
//lagou.jpg
String originalFilename = file.getOriginalFilename();
//4.生成新文件名
//12421321.jpg
String newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
//5.文件上传
String uploadPath = substring + "upload\\";
File filePath = new File(uploadPath, newFileName);
// 如果目录不存在就创建目录
if(!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
System.out.println("创建目录:" + filePath);
}
// 图片就进行了真正的上传
file.transferTo(filePath);
// 6. 将文件名和文件路径返回,进行响应
Map<String, String> map = new HashMap<>();
map.put("fileName",newFileName);
map.put("filePath","http://localhost:8080/upload/" + newFileName);
ResponseResult responseResult = new ResponseResult(true, 200, "图片上传成功", map);
return responseResult;
}
节选自拉钩教育JAVA系列课程