package top.xyquan.ecomdmbbackend.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import top.xyquan.ecomdmbbackend.modules.sys.file.config.OssConfig; import top.xyquan.ecomdmbbackend.modules.sys.file.config.SysFileProperties; import jakarta.annotation.PostConstruct; /** * 系统文件工具类 */ @Component public class SysFileUtils { private static OssConfig staticOssConfig; private static String staticFileAccessDomain; @Autowired private OssConfig ossConfig; @Autowired private SysFileProperties sysFileProperties; @PostConstruct public void init() { staticOssConfig = ossConfig; staticFileAccessDomain = sysFileProperties.getAccessDomain(); } /** * 通过存储路径和存储类型获取文件访问URL * * @param storagePath 存储路径/Key * @param storageType 存储类型(oss/local) * @return 文件访问URL */ public static String getFileAccessUrl(String storagePath, String storageType) { if (storagePath == null || storagePath.isEmpty()) { return null; } if ("oss".equals(storageType)) { // OSS存储:拼接OSS访问域名和存储路径 if (staticOssConfig == null || staticOssConfig.getDomain() == null || staticOssConfig.getDomain().isEmpty()) { return null; } String domain = staticOssConfig.getDomain(); domain = domain.endsWith("/") ? domain.substring(0, domain.length() - 1) : domain; String path = storagePath.startsWith("/") ? storagePath : "/" + storagePath; return domain + path; } else { // 本地存储:拼接 sys.file.access-domain 与路径 if (staticFileAccessDomain == null || staticFileAccessDomain.isEmpty()) { return null; } String domain = staticFileAccessDomain.endsWith("/") ? staticFileAccessDomain.substring(0, staticFileAccessDomain.length() - 1) : staticFileAccessDomain; String path = storagePath.startsWith("./") ? storagePath.substring(2) : storagePath; path = path.startsWith("/") ? path : "/" + path; return domain + path; } } }