spring boot 基礎篇 -- 自帶圖片服務器


  我們平時在日常項目中經常會遇到圖片的上傳和訪問的情景,平時我們可能習慣於把圖片傳到resource或者項項目中的某個位置,這樣會有一個缺點,當我們重新項目打包時,這些圖片會丟失。為了解決這一缺點,我們只有把圖片的路徑放到項目外,而springboot集成了映射項目外路徑的這一功能。ps:當然目前一些大的項目,會有多個子系統都用到文件上傳和下載,這時搭建文件服務器是最好的選擇。

上傳的實現請看:http://www.jb51.net/article/114664.htm 這位大神在里面講的很詳細;

下面請看springboot如何訪問項目外的圖片:

首先要寫個配置類:

application.properties文件中的路徑配置如下

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

配置類如下:

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);
    }
}

注意:如果項目中有攔截器,一定要添加不要攔截圖片路徑,方法如下:

@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.png

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM