关于springboot使用getServletContext().getRealPath(““)获取的是tomcat的临时缓存文件问题

关于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问题

  1. springboot启动后,会把commonDocRoot设置在以下三个位置
    在这里插入图片描述

  2. 如果当前位置下没有这个路径,默认就会创建个临时地址

所以我们手动创建一个路径去存放这个文件,在demo下创建了public,然后getServletContext().getRealPath找到的路径就是当前工程的public
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PneITRYI-1649600607067)(C:\Users\Made\AppData\Roaming\Typora\typora-user-images\image-20220308114808658.png)]

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/");
               
    }
}

成功显示

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值