通常我们的项目代码和上传的文件是分离的,比如项目在 D 盘的某个目录,而图片上传在 E 盘某目录, 那么该如何配置呢
方法一:
创建WebMvcConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { String path = "F:\\java\\uploads\\" ; // 上传路径映射 会使spring boot的自动配置失效 registry.addResourceHandler( "/uploads/**" ).addResourceLocations( "file:" + path); registry.addResourceHandler( "/**" ).addResourceLocations( "classpath:/static/" ); super .addResourceHandlers(registry); } } |
浏览器访问 http://localhost:8080/uploads/1.jpg 可以显示图片
方法二:
配置application.yml
1 2 3 4 5 6 7 8 9 10 | #spring配置 spring : #配置视图 mvc : view : prefix : /WEB-INF/views/ suffix : .jsp resources : static-locations : classpath:/static/, file:F:/java/ #意思是 根目录直接可以访问/static/或者F:/java/下的静态文件如图片,css等 |
file:是因为指定的是一个具体的硬盘路径,其他的使用
浏览器访问 http://localhost:8080/uploads/1.jpg 可以显示图片