springboot解决设置虚拟路径映射绝对路径
应用场景:
项目中加了springboot
//request.getServletContext().getRealPath("/upload"); 获取到的是springboot对应的tomcat的临时路径
package com.example.book.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; //已经过时,两种都试过了,这种没生效
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
registry.addResourceHandler("/upload/**").addResourceLocations("file:C:/Project/book/src/main/resources/upload/");
}
}
//配置成功极为访问 localhost:端口/upload/图片名称-->C:/Project/book/src/main/resources/upload/图片名称(图片上传成功的位置)