咱們平時在平常項目中常常會遇到圖片的上傳和訪問的情景,平時咱們可能習慣於把圖片傳到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