第一种方式、在配置文件application.properties,添加配置
资源映射地址为file:D://User/,图片存放的真实路径
spring.resources.static-locations=file:D://User/
资源映射路径为/image/**,你想在url访问的请求路径
spring.mvc.static-path-pattern=/image/**
第二种方式、在代码上添加配置项文件
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResourceHandler是指你想在url请求的路径
//addResourceLocations是图片存放的真实路径
registry.addResourceHandler("/image/**").addResourceLocations("file:D://User/");
super.addResourceHandlers(registry);
}
}
举例说明:
例如1:文件的真实路径是:D://User/ 123.png,访问路径:localhost:8080/image/123.png
如果项目设置根目录:(java为根目录名称)访问地址为localhost:8080/java/image/123.png
例如2:文件真实路径是:D://User/ png/123.png,访问路径:localhost:8080/image/png/123.png
如果项目设置根目录:(java为根目录名称)访问地址为localhost:8080/java/image/png/123.png
上面两种方式,我是比较喜欢第二种,配置多个路径时,第二种相对于第一种配置更方便、简单