spring boot 自定義規則訪問獲取內部或者外部靜態資源圖片

你笑的像一條狗發表於2019-01-30

###專案中需要將圖片放在磁碟上,不能將圖片放在webapp下面!

springboot預設配置基本上可以滿足我們的日常需要 但是專案中大量使用者上傳的圖片,不能放在tomcat下面,這樣子每次重新部署專案的時候,圖片就失效了,很是麻煩。

所以此時就需要自定義配置springboot的專案靜態檔案對映

springboot預設的配置規則

對映 /** 到

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
複製程式碼

到本地檔案路徑也就是 resource/static/ 下面 訪問時可以: localhost:8080/+資源路徑+資源名

例如我的專案結構!

在這裡插入圖片描述

此時我訪問的靜態資源為:

localhost:8080/js/jquery.min.js

如果配置 jquery.min.js 直接在static下面 訪問則是

localhost:8080/jquery.min.js

但現在需要自定義對映規則:

有兩種方法一種是基於配置檔案,另一種是基於程式碼層面配置。

1 基於配置檔案

#配置內部訪問地址和外部圖片訪問地址 /myimgs/**
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:C:/Users/tizzy/Desktop/img/,classpath:/static/

複製程式碼

對映 /** 到 本地磁碟路徑下存放的圖片,和tomcat中的圖片路徑

訪問路徑則是

  localhost:8080/jquery.min.js
  localhost:8080/ 圖片名
複製程式碼

2 基於程式碼層面配置

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

               //addResourceHandler是指你想在url請求的路徑
               //addResourceLocations是圖片存放的真實路徑

        registry.addResourceHandler("/**").addResourceLocations("file:C:/Users/tizzy/Desktop/img/").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
}

複製程式碼

相關文章