关于springboot使用getServletContext().getRealPath(“”)获取的是tomcat的临时缓存文件问题
String realPath = session.getServletContext().getRealPath("");//获取的是tomcat的文件
问题情境:
- 我在ssm的环境下使用这个,所得到的路径是当前项目路径
F:\work\campus_platform\out\artifacts\campus_platform_war_exploded\
- 而在springboot环境下拿到的是tomcat的临时文件的路径,这就导致每次启动项目,路径就会发生改变,更新上传的头像图片都会没了。
解决这个情况:
第一种:换方法)doge
我直接不用getServletContext().getRealPath(“”)获取路径,直接使用本地绝对路径+资源映射的方式存储和获取
1.不用getRealPath(“”)方式获取路径,直接给项目所在的绝对路径的target文件,或者本地文件哪里都可以
File dir = new File("/F:/project/demo/target/classes/static/upload/");
if(!dir.exists()){ //检测目录是否存在
dir.mkdirs(); //创建当前的目录
}
2.定制化WebMvcConfigurer
当访问/upload/**路径下,会去Locations的路径文件上找
@Configuration
public class AdminConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//访问的路径 当访问/upload/**路径下,会去Locations的路径文件上找
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:F:/project/demo/target/classes/static/upload/"); //本地路径
}
}
数据库存储格式
@RequestMapping("/uploadAvatar")
public JsonResult<String> uploadAvatar(@RequestParam("file") MultipartFile file,
HttpSession session, HttpServletRequest request){
//一、.session中获取id和username
Integer uid = Integer.valueOf(session.getAttribute("uid").toString());
String username = session.getAttribute("username").toString();
//二.判断文件
//1.判断文件是否为空
if (file.isEmpty()){
throw new FileEmptyException("文件为空");
}
//2.文件类型判断
String contentType = file.getContentType();
//2.1如果类型在集合中,返回true
if (!AVATAR_TYPE.contains(contentType)){
throw new FileTypeException("文件类型不支持");
}
//3.判断文件大小
if (file.getSize() > AVATAR_MAX_SIZE){
throw new FileSizeException("文件超出限制");
}
//三、获取路径
//1.直接创建路径
File dir = new File("/F:/project/demo/target/classes/static/upload/");
if(!dir.exists()){ //检测目录是否存在
dir.mkdirs(); //创建当前的目录
}
//2.uuid+文件.后缀
String originalFilename = file.getOriginalFilename();
int index = originalFilename.lastIndexOf(".");
String suffix = originalFilename.substring(index);
String uuidName = UUID.randomUUID().toString().toUpperCase();
String fileName = uuidName + suffix;
//四、调用multipartfile,文件上传
File dest = new File(dir,fileName);
System.out.println("dest:"+dest);
try {
file.transferTo(dest);
} catch (FileStateException e) {
throw new FileStateException("文件状态异常");
} catch (IOException e) {
throw new FileUploadIOException("文件读写异常");
}
//五、将路径传递至sql保存
String avatar = "/upload/"+ fileName;
userService.changeAvatar(uid,avatar,username);
//返回用户头像的路径给前端
System.out.println("avatar路径:"+avatar);
return new JsonResult<String>(HttpState.Ok,avatar);
}
第二种:解决getServletContext().getRealPath问题
-
springboot启动后,会把commonDocRoot设置在以下三个位置
-
如果当前位置下没有这个路径,默认就会创建个临时地址
所以我们手动创建一个路径去存放这个文件,在demo下创建了public,然后getServletContext().getRealPath找到的路径就是当前工程的public
3.定制化WebMvcConfigurer
当访问/upload/**路径下,会去Locations的路径文件上找
@Configuration
public class AdminConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//访问的路径 当访问/upload/**路径下,会去Locations的路径文件上找
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:F:/project/demo/public/upload/");
}
}
成功显示