图片上传到服务器,两种路径选择方式:
选择路径的原因:如果选择绝对路径,图片会存在项目根目录下,这样的弊端是,如果项目重新发布,连带着旧项目的图片一并删掉了,除非手动先保存别的地方再拿过来。
选择相对路径,图片可以放在tomcat的webapps下面,这样的好处是,更新项目,图片还是存在的,但是访问的时候还得对tomcat的server.xml进行配置才能访问
配置如下:
server.xml的里面添加
docBase=“linux环境里tomcat存放的路径”
<Context path="" docBase="/home/usr/tomcat" debug="0" reloadable="false"/>
1、绝对路径:完整的描述文件位置的路径
/*** 获得上传目录的完整路径,如果目录不存在则创建目录** @return*/public static String getRealPath1(String path) {String fileRealPathDir = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath(path);File pathFile = new File(fileRealPathDir);if (!pathFile.exists()) {pathFile.mkdirs();}return fileRealPathDir;}
D:\apache-tomcat-8.0.35-windows-x64\apache-tomcat-8.0.35\webapps\web\files\47aa8ea9-60b0-4140-9d36-6489d156154d.jpg"
2、相对路径:…/img/photo.jpg
/*** 获得上传目录的完整路径,如果目录不存在则创建目录* * @return*/public static String getRealPath(String path) {File pathFile = new File("../file/attachment", path);if(! pathFile.exists()){pathFile.mkdirs();}return pathFile.getAbsolutePath();}
C:\Users\Desktop…\file\attachment\files\6c556b5c-3b2d-4071-96f6-1d76f00cbe06.jpg"