不使用request对象获取项目物理路径

场景:在service层将生成的图片上传到项目根路径下的upload文件夹,由于在service中获取不到request对象,所以可以使用下面代码,通过调用getWebRootPath方法获取项目实际物理路径。

/**
     * 获得工程的WebRoot根目录
     * @return String
     */
    public String getWebRootPath() {
        try {
            String classpath = getClasspath();// classes 目录的物理路径
            String webInfoPath = new File(classpath).getParent();// WEB-INF 目录的物理路径
            return new File(webInfoPath).getParent();// WebRoot 目录的物理路径
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public String getClasspath() {
        try {
            return Class.forName("com.runlion.shop.service.led.BxClientService").getResource("/").getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

上传图片实例:
将图片上传到项目根目录下的/upload/temp文件夹下

String savePath = getWebRootPath()+File.separator;
savePath = savePath + "upload" + File.separator + "temp"+ File.separator;
String fileName = UUID.randomUUID().toString()+".png";
String imagePath = savePath+fileName;
ImageIO.write(image, "png", new File(imagePath));

File.separator是系统默认的文件分隔符
File.separator 的作用相当于 ' \  ' 在 windows 中文件分隔符 用 ' \ ' 或者 ' / ' 都可以,但是在 Linux 中,是不识别 ' \ '  的,而 File.separator是系统默认的文件分隔符号,在 UNIX 系统上,此字段的值为 ' / ', 在 Microsoft Windows 系统上,它为 ' \ ' 屏蔽了这些系统的区别。所以用 File.separator 保证了在任何系统下不会出错。