1、需求來源
圖檔的上傳後并顯示在頁面
2、技術基礎
使用springboot,此處樓主使用1.5.10.RELEASE。(2.0版本也行,已測)
3、思路方案
1)檔案存的基本思路
樓主上傳的檔案放在F盤的某個目錄下,資料庫存的是某目錄下的檔案路徑,此處可看做是圖檔路徑。即F:\logs\platLogo\1552294228766.png,圖檔存的絕對路徑。
2)檔案取的基本思路
項目部署後,我們不知道項目具體的檔案存放位置,也不能使用絕對路徑來擷取檔案,這裡就難住了我。于是樓主就想,怎麼将絕對路徑轉化為相對路徑,通過項目通路就可以擷取檔案。
4、解決措施
檢視資料,發現springboot可以配置檔案的映射。如下面代碼:
@Configuration
public class WebMvcConfg extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/web/**").addResourceLocations("file:F:/logs");
super.addResourceHandlers(registry);
}
}
簡單說明:"file:F:/logs" 表示本地檔案的路徑,"/web/**"表示項目通路的路徑,即http://localhost:8900/web/ 。如我要通路本地的檔案,在浏覽器上輸入:F:\logs\platLogo\1552294228766.png,就可以通路。通過springboot檔案映射後,可以這樣通路:http://localhost:8900/web/platLogo/1552294228766.png.這樣我們就可以在頁面顯示圖檔。
5、代碼共享
1)向前端傳回實體
@ApiOperation(value="擷取平台資訊/播放插件版本号")
@GetMapping(value = "/getPlatMsg")
@ApiImplicitParam(name = "type", value = "類型:2 表示 播放插件,3 表示logo", required = true)
public ApiResponse<SysconfigPlugVo> getPlatMsg(String type) {
if (StrUtil.isBlank(type)){
return new ApiResponse<SysconfigPlugVo>().error("類型不能為空");
}
SysconfigPlugVo item = sysconfigPlugService.getDownloadParam(type);
if (item != null && StrUtil.isBlank(item.getPath())){
return new ApiResponse().error("請上傳logo圖檔");
}
return new ApiResponse().ok().setData(item);
}
2)前端展示
前端使用的vue, 這裡的api是前端配置通路後端的接口的ip+端口,web是映射的路徑
getPlatformMsg(){
this.$ajax.get(`/api/sysconfigParam/getPlatMsg`, {'params': {type: 3}}).then(res => {
if (res.data.code === this.hdConst.OK) {
let param = res.data.data
let imgUrl = '/api/web/'+param.path
let imgName = param.name
}
})
},
6、心得
此處的關鍵是檔案路徑的映射,映射環境配置好了,傳回路徑到前端,前端可以根據路徑實作圖檔的顯示或者檔案的下載下傳。小小例子,記錄一下。
7、項目位址(多種圖檔顯示總結)
https://github.com/krycai/Allen-projects/tree/master/allen-upload