Java SpringBoot 图片上传无法马上显示,只能重启IDEA后才生效解决方案

当上传图片时不能马上显示,后台接收图片保存到本地,返回保存路径,发现页面的标签无法显示图片,F12显示无法加载图片,请求地址为ip:port/static/images/(我将图片保存到了static下),显示404无此资源。将项目重新启动之后,图片可以正常加载。
原因分析:当程序加载后自动会加载到内存中,对当前目录不做读取。
解决方案就是设置虚拟目录

 1 package com.ls.config;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 6 
 7 /**
 8  * @author lishuai
 9  * @create 2022-04-13 21:16
10  */
11 @Configuration
12 public class MyPicConfig implements WebMvcConfigurer {
13     @Override
14     public void addResourceHandlers(ResourceHandlerRegistry registry){
15         registry.addResourceHandler("/images/**").
16                 addResourceLocations("file:" + System.getProperty("user.dir") + "/src/main/resources/static/images/");
17     }
18 }

 

然后解决问题
addResourceHandler()里配置需要映射的文件夹,此处代表映射文件夹user下的所有资源。
addResourceLocations()配置文件夹在系统中的路径,使用绝对路径,格式为“file:你的路径” (注意这里)

为了防止路径有问题,我们还可以这样,这样就再也不怕路径出问题了。换到其它电脑上也没有问题

 


原文链接:https://blog.csdn.net/weixin_44690195/article/details/108855892

 

posted @ 2022-04-13 21:27  谜语+  阅读(1070)  评论(0编辑  收藏  举报