# 记录Spring boot上传图片后不能立即显示的原因及解决方法(读取当前项目下的图片)
我遇到的问题:
图片上传到项目根目录下,前端无法立即展示,但是切换回idea后端代码,看见上传的文件在根目录出现后,再切换回浏览器就能访问此图片.
网上看过很多文章,基本上都是说是缓存问题
其实不然,根本原因:因为对服务器的保护措施导致的,服务器不能对外部暴露真实的资源路径,需要配置虚拟路径映射访问。
解决方法
解决方法:
1、首先配置好spring boot目录下的application.yml,相关配置如下。
spring:
resources:
static-locations:
- classpath:/static/
2、建立ImagesUploadConfig类,实现WebMvcConfigurer接口。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ImagesUploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//获取文件的真实路径
String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\uploadFile\\";
//uploadFile对应resource下工程目录
registry.addResourceHandler("/uploadFile/**").addResourceLocations("file:"+path);
}
}
找到的原文连接: https://blog.csdn.net/welingfeng1/article/details/105370696