问题描述:
页面上传图片文件,后台接收图片保存到本地,保存到项目下的static/asserts/img下。浏览器请求地址为ip:port/asserts/**,发现页面的<img>标签无法显示图片,F12显示404无此资源。将项目重新启动之后,图片可以正常加载。
**解决方法:**需要配置虚拟文件路径的映射
这是一种保护机制,为了防止绝对路径被看出来,目录结构暴露
添加一个config类,将虚拟路径向绝对路径映射
package com.ckh.springboot04.config;
import com.ckh.springboot04.component.MyLocaleResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//继承WebMvcConfigurer扩展mvc
//用于往容器中添加组件
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//上传地址
@Value("${file.upload.path}")
private String filePath;
//显示相对地址
// @Value("${file.upload.path.relative}")
// private String fileRelativePath;
/**
* 资源映射路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//一访问/images/**,就找filePath下的路径
registry.addResourceHandler("/img/**").addResourceLocations("file:/" + filePath);
}
}
配置文件:
# 声明图片保存的绝对路径
file.upload.path=F://项目地址/src/main/resources/static/asserts/img/
参考博客:https://blog.csdn.net/zx874561/article/details/104521787