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

网友投稿 502 2023-04-17


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.sprihttp://ngframework.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 = imagehttp://sPath.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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:mybatis中使用oracle关键字出错的解决方法
下一篇:MyBatis 延迟加载、一级缓存、二级缓存(详解)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~