當上傳圖片時不能馬上顯示,后台接收圖片保存到本地,返回保存路徑,發現頁面的標簽無法顯示圖片,F12顯示無法加載圖片,請求地址為ip:port/static/images/(我將圖片保存到了static下),顯示404無此資源。將項目重新啟動之后,圖片可以正常加載。
原因分析:當程序加載后自動會加載到內存中,對當前目錄不做讀取。
解決方案就是設置虛擬目錄
1 package com.ls.config; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 7 /** 8 * @author lishuai 9 * @create 2022-04-13 21:16 10 */ 11 @Configuration 12 public class MyPicConfig implements WebMvcConfigurer { 13 @Override 14 public void addResourceHandlers(ResourceHandlerRegistry registry){ 15 registry.addResourceHandler("/images/**"). 16 addResourceLocations("file:" + System.getProperty("user.dir") + "/src/main/resources/static/images/"); 17 } 18 }
然后解決問題
addResourceHandler()里配置需要映射的文件夾,此處代表映射文件夾user下的所有資源。
addResourceLocations()配置文件夾在系統中的路徑,使用絕對路徑,格式為“file:你的路徑” (注意這里)
為了防止路徑有問題,我們還可以這樣,這樣就再也不怕路徑出問題了。換到其它電腦上也沒有問題
原文鏈接:https://blog.csdn.net/weixin_44690195/article/details/108855892