我們平時(shí)在日常項(xiàng)目中經(jīng)常會(huì)遇到圖片的上傳和訪問(wèn)的情景,平時(shí)我們可能習(xí)慣于把圖片傳到resource或者項(xiàng)項(xiàng)目中的某個(gè)位置,這樣會(huì)有一個(gè)缺點(diǎn),當(dāng)我們重新項(xiàng)目打包時(shí),這些圖片會(huì)丟失。為了解決這一缺點(diǎn),我們只有把圖片的路徑放到項(xiàng)目外,而springboot集成了映射項(xiàng)目外路徑的這一功能。ps:當(dāng)然目前一些大的項(xiàng)目,會(huì)有多個(gè)子系統(tǒng)都用到文件上傳和下載,這時(shí)搭建文件服務(wù)器是最好的選擇。
上傳的實(shí)現(xiàn)請(qǐng)看:Spring Boot實(shí)現(xiàn)圖片上傳功能 這位大神在里面講的很詳細(xì);
下面請(qǐng)看springboot如何訪問(wèn)項(xiàng)目外的圖片:
首先要寫(xiě)個(gè)配置類(lèi):
application.properties文件中的路徑配置如下
cbs.imagesPath=file:/E:/imagesuuuu/
配置類(lèi)如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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(這里用一句話描述這個(gè)類(lèi)的作用) * @author Administrator * @date 2017年7月11日 */ @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { //獲取配置文件中圖片的路徑 @Value ( "${cbs.imagesPath}" ) private String mImagesPath; //訪問(wèn)圖片方法 @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); } } |
注意:如果項(xiàng)目中有攔截器,一定要添加不要攔截圖片路徑,方法如下:
1
2
3
4
5
6
7
|
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor( new LoginInterceptor()).addPathPatterns( "/api/**" ).excludePathPatterns( "/api/getLogin" ) .excludePathPatterns( "/api/getExit" ); super .addInterceptors(registry); } |
這樣啟動(dòng)項(xiàng)目就可以獲取路徑下的圖片了:訪問(wèn)地址例如:localhost:8080/images/123.png
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/bestxyl/p/7403297.html