目的:
把上传至服务器指定物理磁盘相关目录(绝对路径)的文件通过浏览器直接访问预览。
这种具体实现其实是要配置一个映射关系的,即配置一个虚拟路径来映射文件的真实绝对路径(完美的隐藏了文件的真实物理路径,可以说不但很安全,而且外网可以直接访问)。
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
String os = System.getProperty("os.name");
//如果是Windows系统
if (os.toLowerCase().startsWith("win")) {
registry.addResourceHandler("/app_file/**")
// /app_file/**表示在磁盘filePathWindow目录下的所有资源会被解析为以下的路径
.addResourceLocations("file:" + filePathWindow);
} else { //linux 和mac
registry.addResourceHandler("/app_file/**")
.addResourceLocations("file:" + filePathLinux) ;
}
super.addResourceHandlers(registry);
}
注:
- 编写类继承WebMvcConfigurerAdapter类,重写该类的addResourceHandlers方法;其中addResourceHandler指向映射路径,addResourceLocations指向资源文件路径;资源文件路径地址必须以/结尾,指向文件目录上一层
- 还可以在addResourceHandlers方法中写多套映射策略
class WebConfigurer extends WebMvcConfigurerAdapter {
@Autowired
BootdoConfig bootdoConfig;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//图片资源
registry.addResourceHandler("/files/**").addResourceLocations("file:///"+"/Users/fanzhen/Documents/ideaworkspaces/bootdo/bootdo/uploaded_files/");
//文档资源
registry.addResourceHandler("/docs/**").addResourceLocations("file:///"+"/Users/fanzhen/Documents/ideaworkspaces/bootdo/bootdo/uploaded_files/docs/");
super.addResourceHandlers(registry);
}
}