package top.xyquan.ecomdmbbackend.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import top.xyquan.ecomdmbbackend.modules.sys.file.config.OssConfig; import jakarta.annotation.PostConstruct; /** * 系统文件工具类 */ @Component public class SysFileUtils { private static OssConfig staticOssConfig; private static String staticFileAccessDomain; @Autowired private OssConfig ossConfig; @Value("${file.access-domain:}") private String fileAccessDomain; @PostConstruct public void init() { staticOssConfig = ossConfig; staticFileAccessDomain = fileAccessDomain; } /** * 通过存储路径和存储类型获取文件访问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 { // 本地存储:拼接文件访问域名和存储路径 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; } } }