最近在做的一個項目中有一個比較奇葩的需求:
要在springboot中,上傳本地的圖片進行展示
我的第一反應是,直接在數據庫字段加一個存儲本地路徑的字段,然后用thymeleaf的th:src渲染到前端就好了嘛!
理想很豐滿,但現實卻很骨感~
前端報了這樣的錯誤Not allowed to load local resource
于是我想到了可以使用IO將圖片先上傳到static/images目錄下,這樣就不會出現禁止訪問本地路徑的問題了
但是這樣實現,問題又來了:上傳后的圖片必須重啟springboot,才能進行展示,否則無法加載
這個應該是因為springboot在初始化時加載靜態資源,運行時導入的資源只能在再次初始化時加載
于是,我苦思冥想,查閱了多方資料,終于使用本地虛擬路徑的方式,解決了這個問題
正片開始:
1.首先配置一個配置類
1
2
3
4
5
6
7
8
9
10
11
|
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/image/**" ).addResourceLocations( "file:E:/vote_images/" ); } } |
addResourceHandler是指你設置的虛擬路徑,前端展示頁面時填入這個路徑來進行訪問
addResourceLocations是指實際的本地路徑,你需要代理給虛擬路徑來訪問的路徑
2. IO實現文件上傳
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//如果文件夾不存在,創建文件夾 File file= new File( "E:\\vote_images" ); if (!file.exists()){ file.mkdir(); } //文件的上傳 try (InputStream input = new FileInputStream( new File(judge)); OutputStream output = new FileOutputStream( "E:\\vote_images\\" + num + ".jpg" ) ) { byte [] buf = new byte [ 1024 ]; int bytesRead; while ((bytesRead = input.read(buf)) != - 1 ) { output.write(buf, 0 , bytesRead); } } catch (IOException e) { e.printStackTrace(); } //設置路徑字段 o.setPath( "\\image\\" + (num++) + ".jpg" ); //增加數據 optionsService.insert(o); |
3.前端渲染頁面
1
|
< img height = "150px" width = "225px" th:src = "@{${opt.getPath()}}" > |
這樣就成功實現需求啦
到此這篇關于基于Springboot2.3訪問本地路徑下靜態資源的方法的文章就介紹到這了,更多相關Springboot2.3訪問本地靜態資源內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/YzVermicelli/article/details/106618800