标签:String,filePath,substring,newFileName,file,上传,图片 From: https://www.cnblogs.com/zyb-luckey/p/18068227
/*
课程图片上传
*/
@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;
}