前言
今天在幫朋友看文件上傳問題的時候,發現上傳的文件雖然上傳到本地路徑或者項目文件下了,但是訪問卻訪問不到,要重新啓動項目纔可以。
找了下網上的解決方案,不一而足,在此收集我試了可以用的方案
文件存儲在編譯文件下
按下面這個代碼可以將文件存在編譯文件下 ,也就是target/classes下面
String path = "/static/upload/"; File file1 = null; try { file1 = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { // nothing to do } if (file1 == null || !file1.exists()) { file1 = new File(""); } String savePath = file1.getAbsolutePath()+path;
不過這樣並沒有存儲在項目下,所以項目如果clean一下那麼這些文件將都會消失,不過對與某些項目來說只有開始和停止,也並沒有重新部署的必要。
或者完全可以利用這一特點,存儲臨時文件,項目重新編譯時文件消失。
配置訪問虛擬路徑
文件實際是存在e盤的path路徑下面,但是當訪問http://ip:port/upload/xxx.jpg時,虛擬路徑會映射到file://e:/path/xxx.jpg的路徑中訪問文件。也是對服務器文件的一種保護措施吧.
啓動類集成WebMvcConfigurationSupport
@SpringBootApplication public class DemoApplication extends WebMvcConfigurationSupport { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("config啓動了"); //項目路徑 //String savePath = "\\src\\main\\resources\\static\\upload\\"; //String path = System.getProperty("user.dir")+savePath; //本地路徑 String path = "e:/path/"; registry.addResourceHandler("/upload/**").addResourceLocations("file:"+path); } }
實現配置類WebMvcConfigurer
@Configuration public class MyPicConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("config啓動了"); //項目路徑 //String savePath = "\\src\\main\\resources\\static\\upload\\"; //String path = System.getProperty("user.dir")+savePath; //本地路徑 String path = "e:/path/"; registry.addResourceHandler("/upload/**").addResourceLocations("file:"+path); } }