SpringBoot配置项目访问路径URL的根路径,并访问项目本地图片
配置项目跟路径,默认localhost:8080,如添加了项目访问跟路径,上传文件返回的URL也需要包含此路径(没配置就不用写)
1、SpringBoot在2.0之前版本使用server.context-path
server.context-path=/demo
2、SpringBoot在2.0之后版本使用server.servlet.context-path
server.servlet.context-path=/demo
spring:
# 启动环境 Dev|Test|Prod
profiles:
active: Dev
freemarker:
#模板引擎缓存
cache: true
#本地文件上传到的路径
resources:
static-locations: file:E:/demo/uploadPath/
#文件对外暴露的访问路径
mvc:
static-path-pattern:
新建一个类,类名随意,实现WebMvcConfigurer 重写addResourceHandlers方法
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(staticPrefix)
.setCacheControl(CacheControl.maxAge(cacheTime, TimeUnit.DAYS).cachePublic());/flowable
registry.addResourceHandler("/profile/**").addResourceLocations("file:" + FileUploadConfig.getProfile());
/** swagger配置 */
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(LicenseCheckInterceptor).addPathPatterns("/**")
.excludePathPatterns("/static/**","/authInsu/**", "/profile/**","/image/**");
registry.addInterceptor(securityKeyInterceptorAdapter).addPathPatterns("/**");
registry.addInterceptor(lockHandlerInterceptorAdapter).addPathPatterns("/**");
registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
if(ToolUtil.isNotEmpty(adapterRegistry)){
for(String key: adapterRegistry.keySet()){
registry.addInterceptor(SpringUtil.getBean(key)).addPathPatterns(adapterRegistry.get(key));
}
}
}
}
http://localhost:8080:输入你自己的ip地址和端口,demo:是我自己项目登录访问路径
@Controller
@RequestMapping("/uploadFile")
public class UploadFileController {
@PostMapping("/uploadFile")
@ResponseBody
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
try
{
String filePath = FileUploadConfig.getUploadPath();
String fileName = FileUploadUtils.upload(filePath, file);
String url = fileName;
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("code","0");
resultMap.put("msg","上传成功");
resultMap.put("data",url);
resultMap.put("count",0);
return resultMap;
}
catch (Exception e){
e.printStackTrace();
return error("上传失败");
}
}
}