配置WebMvcConfigurer无法解决“SpringBoot 图片上传无法马上显示,只能重启IDE后才生效”
网络上很多关于“SpringBoot 图片上传无法马上显示,只能重启IDE后才生效”的解决方案,基本是通过配置WebMvcConfigurer来解决,可参见配置WebMvcConfigurer
但是在配置完成后仍然无法解决这个问题,比较了我和博主的不同点,发现在目录结构上。
我的诉求是将图片保存到img下的newProd文件夹中,而博主相当于保存到img文件夹中,这时WebMvcConfigurer的配置应该如下所示:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @description: webmvc配置资源映射路径
* @create: 2022-06-10 13:57
**/
/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").
addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/resources/static/img/");
}
}
而不是
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/newProd/**").
addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/resources/static/img/newProd/");
}
控制器层再加上newProd子目录写入文件:
// 获取上传文件名
String filename = file.getOriginalFilename();
String suffixName = filename.substring(filename.lastIndexOf("."));
// 定义上传文件保存路径
String filePath = "C:/Users/Administrator/teatour/src/main/resources/static/img/";
String path = filePath + "newProd/";
//生成新的文件名称
String newImgName = newProd.getId().toString() + suffixName;
// 新建文件
File filepath = new File(path, newImgName);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
try {
// 写入文件
file.transferTo(new File(path + File.separator + newImgName));
} catch (IOException e) {
e.printStackTrace();
}