最近在做的一個(gè)項(xiàng)目中有一個(gè)比較奇葩的需求:
要在springboot中,上傳本地的圖片進(jìn)行展示
我的第一反應(yīng)是,直接在數(shù)據(jù)庫字段加一個(gè)存儲(chǔ)本地路徑的字段,然后用thymeleaf的th:src渲染到前端就好了嘛!
理想很豐滿,但現(xiàn)實(shí)卻很骨感~
前端報(bào)了這樣的錯(cuò)誤Not allowed to load local resource
于是我想到了可以使用IO將圖片先上傳到static/images目錄下,這樣就不會(huì)出現(xiàn)禁止訪問本地路徑的問題了
但是這樣實(shí)現(xiàn),問題又來了:上傳后的圖片必須重啟springboot,才能進(jìn)行展示,否則無法加載
這個(gè)應(yīng)該是因?yàn)閟pringboot在初始化時(shí)加載靜態(tài)資源,運(yùn)行時(shí)導(dǎo)入的資源只能在再次初始化時(shí)加載
于是,我苦思冥想,查閱了多方資料,終于使用本地虛擬路徑的方式,解決了這個(gè)問題
正片開始:
1.首先配置一個(gè)配置類
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是指你設(shè)置的虛擬路徑,前端展示頁面時(shí)填入這個(gè)路徑來進(jìn)行訪問
addResourceLocations是指實(shí)際的本地路徑,你需要代理給虛擬路徑來訪問的路徑
2. IO實(shí)現(xiàn)文件上傳
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//如果文件夾不存在,創(chuàng)建文件夾 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(); } //設(shè)置路徑字段 o.setPath( "\\image\\" + (num++) + ".jpg" ); //增加數(shù)據(jù) optionsService.insert(o); |
3.前端渲染頁面
1
|
< img height = "150px" width = "225px" th:src = "@{${opt.getPath()}}" > |
這樣就成功實(shí)現(xiàn)需求啦
到此這篇關(guān)于基于Springboot2.3訪問本地路徑下靜態(tài)資源的方法的文章就介紹到這了,更多相關(guān)Springboot2.3訪問本地靜態(tài)資源內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/YzVermicelli/article/details/106618800