使用:
例子:存放图片的本地路径:E:\Work\project\springboot\resource\images
数据库存放路径:2024-04-26/1714111785680.png
ServiceConfig.getImageBaseUrl() + 数据库存放路径
最终结果:http://ip地址:8090/api/resource/images/2024-04-26/1714111785680.png
1、配置类
/**
* 静态资源
* @author songxue
* @date 2024/2/20 14:13
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件夹 **是所有
registry.addResourceHandler("/resource/**")
//GlobalVariate.projectPath 文件路径
.addResourceLocations("file:" + GlobalVariate.projectPath + "/");
}
}
2、完整代码
import com.huiyu.common.server.GlobalVariate;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
public class ServiceConfig implements ApplicationListener<WebServerInitializedEvent> {
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
// 项目启动获取启动的端口号
ServiceConfig.serverPort = event.getWebServer().getPort();
}
/**
* 当前服务使用的端口号
*/
private static int serverPort;
public static int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort) {
ServiceConfig.serverPort = serverPort;
}
/**
* 获取请求基地址(自己搭建的服务器会有一定几率访问不到ip,如果是云服务器建议写死)
*
* @return String 请求基地址
**/
public static String getBaseUrl() {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "http://" + GlobalVariate.serverIp + ":" + getServerPort();
}
/**
* 获取图片前缀
*
* @return String 图片前缀
**/
public static String getImageBaseUrl() {
//api是因为我的yml配置了context-path: /api 无配置可不加
return "http://" + GlobalVariate.serverIp + ":" + getServerPort() + "/api/resource/images/";
}
}