spring boot 基础篇 -- 自带图片服务器

  咱们平时在平常项目中常常会遇到图片的上传和访问的情景,平时咱们可能习惯于把图片传到resource或者项项目中的某个位置,这样会有一个缺点,当咱们从新项目打包时,这些图片会丢失。为了解决这一缺点,咱们只有把图片的路径放到项目外,而springboot集成了映射项目外路径的这一功能。ps:固然目前一些大的项目,会有多个子系统都用到文件上传和下载,这时搭建文件服务器是最好的选择。web

上传的实现请看:http://www.jb51.net/article/114664.htm 这位大神在里面讲的很详细;spring

下面请看springboot如何访问项目外的图片:api

首先要写个配置类:springboot

application.properties文件中的路径配置以下服务器

cbs.imagesPath=file:/E:/imagesuuuu/

配置类以下:app

package bp.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);
    }
}

注意:若是项目中有拦截器,必定要添加不要拦截图片路径,方法以下:ide

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/api/**").excludePathPatterns("/api/getLogin")
                .excludePathPatterns("/api/getExit");
        super.addInterceptors(registry);

    }

 这样启动项目就能够获取路径下的图片了:访问地址例如:localhost:8080/images/123.pngspa

相关文章
相关标签/搜索