SpringBoot启动自带文件服务器,直接访问本机本地文件夹中的图片,或下载文件
问题描述:配置SpringBoot想要直接在浏览器访问文件夹中的图片或者文件。1、本机新建存放文件的路径,我用的F:\vueimg2、SpringBoot项目的application.properties配置文件中,写入cbs.imagesPath=file:/F:/vueimg/配置上自己的路径3、Java创建config包,新建配置文件WebAppConfigpackage com.examp
·
问题描述:配置SpringBoot想要直接在浏览器访问文件夹中的图片或者文件。
1、本机新建存放文件的路径,我用的F:\vueimg
2、SpringBoot项目的application.properties
配置文件中,写入
cbs.imagesPath=file:/F:/vueimg/
配置上自己的路径
3、Java创建config包,新建配置文件WebAppConfig
package com.example.img_manage.config;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @ClassName: WebAppConfig
* @Description: TODO(这里用一句话描述这个类的作用)
* @author Administrator
* @date 2017年7月11日
*/
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
//获取配置文件中图片的路径
@Value("${cbs.imagesPath}")
private String mImagesPath;
//访问图片方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
if(imagesPath.indexOf(".jar")>0){
imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
}else if(imagesPath.indexOf("classes")>0){
imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
}
imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
mImagesPath = imagesPath;
}
LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);
registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
super.addResourceHandlers(registry);
}
}
4、启动SpringBoot项目,访问项目路径,中间加个images
就可以定向到图片或者文件了
运行不出来的看我的文件结构
更多推荐
所有评论(0)