1、实现WebMvcConfigurer接口中addResourceHandlers
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc配置,读取文件
* @author dxf
* */
@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {
// 本地存储路径
String locationPath = "C:/picture/";
@Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
log.info("本地存储路径:" + locationPath);
registry.addResourceHandler("/getFile/**/**").addResourceLocations("file:" + locationPath);
}
}
2、准备图片
图片存储地址需在本地资源存储路径下
3、测试读取
获取文件读取路径:项目部署地址/ + getFile + / + 文件名
示例:http://localhost:8080/getFile/1.jpg
文件读取成功,如果前端要动态获取图片或视频,可以将获取到的文件读取地址放于标签的src下
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div align="center">文件读取测试</div>
<img src="http://localhost:8080/getFile/1.jpg" />
</body>
</html>
读取图片成功:
结尾补充:
如果要更加灵活的获取文件,可以将本地资源存储路径配置和文件读取路径配置在配置文件中,数据库中存储文件名即可,读取文件时只需要 serviceUrl + 文件名,即可读取文件;