問題描述:
文件上傳到磁盤后,如果想要訪問該文件的話,可以通過配置虛擬路徑映射到該磁盤文件進行訪問。
1、在application.properties文件中配置虛擬路徑,需要注意的是,"訪問文件的基本路徑地址"的IP地址和端口號必須和項目的相同
#磁盤文件存儲路徑 file.path=H:/Business/image/ #虛擬路徑 file.static-path=/upload/image/** #訪問文件的基本路徑地址 file.base-url=http://127.0.0.1:8080/upload/image/
2、編寫虛擬路徑配置
import org.springframework.beans.factory.annotation.Value; 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 WebAppMvcConfig implements WebMvcConfigurer { @Value("${file.path}") private String path; @Value("${file.static-path}") private String staticPath; // 如果訪問http://localhost:8080/upload/image/test.jpg // 實則訪問H:/Business/image/test.jpg @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticPath).addResourceLocations("file:"+path);
} }