spring boot通过ip访问本地文件
方案一:
继承WebMvcConfigurerAdapter并重写addResourceHandlers方法(SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废 用WebMvcConfigurer代替)
继承WebMvcConfigurer并重写addResourceHandlers方法
继承WebMvcConfigurationSupport并重写addResourceHandlers方法
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @author Li
* @create 2020/03/13 15:24
*/
@Configuration //此处换继承类(这里只写一个重写方法相同)
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* @param registry 注册表
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("file:F://test//upload/");
}
}
配置之后直接 127.0.0.1:8080/image/1.png 访问
也可以自己在配置文件配置,不用写死:
/**
* 静态资源的配置 - 使得可以从磁盘中读取 Html、图片、视频、音频等
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/" + dirName + "/**").addResourceLocations("file:" + rootPath + "/" + dirName + "/");
registry.addResourceHandler("/**")
.addResourceLocations(staticLocations.split(","));
}
rootFileDir: D:/thunder_fire
local:
#本地文件根路径
dir-name: appfile
root-path: ${rootFileDir}
@Value("${local.root-path}")
private String rootPath;
@Value("${local.dir-name}")
private String dirName;
优先级 貌似为(WebMvcConfigurationSupport)>(WebMvcConfigurer)> yml配置(static-locations)
方案二:
spring:
mvc:
static-path-pattern: /image/**
resources:
static-locations: file:F://test//upload/