栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot自带图片服务器使用详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot自带图片服务器使用详解

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

上传的实现请看:Spring Boot实现图片上传功能 这位大神在里面讲的很详细;

下面请看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;


@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

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144748.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号