看標題好像很簡單的樣子,但是針對使用jar包發布SpringBoot項目就不一樣了。
當你使用tomcat發布項目的時候,上傳文件存放會變得非常簡單,因為你可以隨意操作項目路徑下的資源。但是當你使用SpringBoot的jar包發布項目的時候,你會發現,你不能像以前一樣操作文件了。當你使用File file = new File()的時候根本不知道這個路徑怎么辦。而且總不能很小的項目也給它構建一個文件服務器吧。所以這次就來解決這樣的問題
實現
因為我們無法操作jar包內容,所以我們只能將文件存放在別的位置,與jar包同級的目錄是一個不錯的選擇。
首先獲取根目錄:
File path = new File(ResourceUtils.getURL("classpath:").getPath()); if(!path.exists()) { path = new File(""); }
然后獲取需要的目錄,我們設定我們需要將文件存放在與jar包同級的static的upload目錄下
File upload = new File(path.getAbsolutePath(),"static/upload/"); if(!upload.exists()) { upload.mkdirs(); }
然后當我們要將上傳的文件存儲的時候,按照下面的方式去新建文件,然后使用你喜歡的方式進行存儲就可以了
File upload = new File(path.getAbsolutePath(),"static/upload/test.jpg"); FileUtils.copyInputStreamToFile(inputStream, uploadFile);
不要忘記
你需要在application.yml配置中加入以下代碼,指定兩個靜態資源的目錄,這樣你上傳的文件就能被外部訪問到了。
spring: # 靜態資源路徑 resources: static-locations: classpath:static/,file:static/
/* **author:weijiakun *獲取目錄工具類 */ public class GetServerRealPathUnit { public static String getPath(String subdirectory){ //獲取跟目錄---與jar包同級目錄的upload目錄下指定的子目錄subdirectory File upload = null; try { //本地測試時獲取到的是"工程目錄/target/upload/subdirectory File path = new File(ResourceUtils.getURL("classpath:").getPath()); if(!path.exists()) path = new File(""); upload = new File(path.getAbsolutePath(),subdirectory); if(!upload.exists()) upload.mkdirs();//如果不存在則創建目錄 String realPath = upload + "/"; return realPath; } catch (FileNotFoundException e) { throw new RuntimeException("獲取服務器路徑發生錯誤!"); } } }
springboot項目打成jar包后讀取靜態資源:
1:在非靜態方法中讀取
InputStream stream = getClass().getClassLoader().getResourceAsStream("test/test.txt");
2: 在靜態方法中讀取:
InputStream resourceAsStream = YourClass.class.getClassLoader().getResourceAsStream("static/position.png");
