为什么要配置虚拟路径
- 这是一种保护机制,避免暴露系统真实的目录
- 图片等文件类在服务器端保存最好的做法是单独保存到当前服务器的一个目录中,而不是和代码保存在一起
解决方案
- 新建一个配置类
这里分了两个 一个是windows(本地开发),一个是linux(上线测试)
注意路径根据需要改成自己目录,然后写成 file:绝对路径 的形式
这里的Linux路径自己根据需要提前建一个
package com.example.zl.util;
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 ResourceConfigAdapter implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
//registry.addResourceHandler("/excel/**").addResourceLocations("file:E:\\excel\\");
//虚拟路径映射
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
System.out.println("当前运行环境是" + os);
//win路径需要转义符
registry.addResourceHandler("/excel/**").addResourceLocations("file:E:\\excel\\");
}else{//linux系统
System.out.println("当前运行环境是" + os);
registry.addResourceHandler("/excel/**").addResourceLocations("file:/usr/asset/lou/excel/");
}
}
}
- 改application.yml
server:
port: 8088
servlet:
#虚拟路径映射配置
context-path: /demo
- 后台端口如何访问
因为这里context-path改成了demo,所以需要在原先的路径前加上/demo
如:之前是 http://ip:port/后台端口 现在改成 http://ip:port/demo/后台端口 - 前端如何获取图片
addResourceHandler("/excel/**")
根据这一句知道前边配置的 将 /excel映射到服务器具体的路径
所以前端的访问形式就是
http://ip:port/demo/excel/你的文件名字
就能获取到对应服务器端存储的文件
以Windows为例
即 http://ip:port/demo/excel/ => E:/excel/
5. 支持子目录
比如在windows下,你在 E:/excel下创建了子目录 sub ,并存储了test.jpg
即路径是 E:/excel/sub/test.jpg
前端使用 http://ip:port/demo/excel/sub/test.jpg 同样能获得test.jpg
6. Linux和windows下是一样的,只不过绝对路径不一样。Linux下的目录结构如下,根目录是 /