寫在前面
圖片上傳功能, web項目部署在本地Tomcat上並沒有問題, 但是打成war包部署到Linux服務器Weblogic下卻出現如題問題, 導致圖片上傳失敗.
問題代碼
String realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/") + "/" + path;// 文件的硬盤真實路徑
在Windows下部署到Tomcat沒有問題, 項目打成war包后部署到Weblogic獲取不到項目根目錄.
解決方案
通過獲取class文件所在路徑, 然后對該路徑進行處理.
String rootPath = this.getClass().getResource("/").getPath().replaceAll("^\\/", "");// 獲取到的這個路徑包含/WEB-INF/classes
結果日志
home/weblogic/Oracle/Middleware/user_projects/domains/base_domain/servers/3/tmp/_WL_user/cqyyt/i9yd39/war/WEB-INF/classes/
home前面並沒有"/", 而且還包含"/WEB-INF/classes/"這樣的路徑也不是想要的結果.
最終修改
將獲取到的路徑前加"/", 同時把"/WEB-INF/classes"截取掉.
String rootPath = this.getClass().getResource("/").getPath().replaceAll("^\\/", "");// cnblogs rootPath = StringUtils.substringBeforeLast(rootPath,"/WEB-INF/classes"); logger.info("==============uploadFile 測試獲取項目根目錄 rootPath: "+rootPath); String realPath = "/" + rootPath + "/" + path;// 文件的硬盤真實路徑
到服務器上找, 發現部署后的war包解壓到了路徑下(也就是最終想要的路徑rootPath):
/home/weblogic/Oracle/Middleware/user_projects/domains/base_domain/servers/3/tmp/_WL_user/cqyyt/i9yd39/war
結果日志
效果圖
不明白的地方
奇怪的是這樣寫並不影響Tomcat部署, 本來還在想這樣在路徑前加"/"會影響Windows下Tomcat部署項目圖片上傳, 結果:
第二條數據的照片是本地測試結果, 發現雖然文件保存全路徑前有"/"但是並不影響圖片的上傳?
小結
說到底還是獲取路徑的問題,對已獲取的路徑“改造”是一個思路.