
正文
【记录】spring boot 图片上传与显示
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
问题:spring boot 使用的是内嵌的tomcat, 文件上传指定目录时不知道文件上传到哪个地方,不知道访问路径。
//部署到服务器的tomcat上时通常使用这种方式
request.getServletContext().getRealPath("picture/");
//然而在spring boot中内嵌的tomacat,所以是临时目录,如:C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.7776702262463059617.8080\picture\
spring boot 把静态的文件在启动的时候都会加载到classpath的目录下的,package时把static目录下的资源一起打包成jar包,所以上传的文件不知相对于应用目录在哪,也不知怎么写访问路径合适。
如果上传到项目的static目录下是没有效果的,需要重新build才能访问到。
解决方法:
spring boot 的静态资源默认配置为:
//映射到static(或/public、/resources、/META-INF/resources)目录
spring:
mvc:
static-path-pattern: /**
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/
通过代码修改静态资源配置(这里不能通过配置文件修改,因为会覆盖默认配置):
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//这是系统默认配置
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/");
//这是添加的配置,表示将/picture/..映射到E:/picture/目录
registry.addResourceHandler("/picture/**").addResourceLocations("file:E:/picture/");
super.addResourceHandlers(registry);
}
}
这样在上传时将路径设置为E:/picture/,在访问上传的图片时如/picture/xxx.jpg就能访问到图片了。
参考文章:https://blog.csdn.net/u011144425/article/details/79225864






