修改路径的问题

This commit is contained in:
Jack 2025-12-18 09:29:12 +08:00
parent a4ac7c8d9a
commit 850a4bcb73

View File

@ -7,6 +7,7 @@ import (
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync" "sync"
"github.com/tencentyun/cos-go-sdk-v5" "github.com/tencentyun/cos-go-sdk-v5"
@ -69,12 +70,15 @@ func (c *COSUtil) UploadFile(localFilePath, cosPath string) error {
cosPath = filepath.Base(localFilePath) cosPath = filepath.Base(localFilePath)
} }
// 去除可能的前导斜杠,避免 filepath.Join 忽略 basePath
cosPath = strings.TrimPrefix(cosPath, "/")
// 添加基础路径前缀 // 添加基础路径前缀
if c.basePath != "" { if c.basePath != "" {
cosPath = filepath.Join(c.basePath, cosPath) cosPath = filepath.Join(c.basePath, cosPath)
} }
// 规范化路径分隔符 // 规范化为 POSIX 分隔cos 要求对象 key 为 '/')
cosPath = filepath.ToSlash(cosPath) cosPath = filepath.ToSlash(cosPath)
// 打开本地文件 // 打开本地文件
@ -142,8 +146,10 @@ func (c *COSUtil) UploadDirectory(localDir, cosDir string) error {
return fmt.Errorf("计算相对路径失败: %v", err) return fmt.Errorf("计算相对路径失败: %v", err)
} }
// 构造COS路径 // 构造COS路径(去除前导斜杠并统一为 /
cosPath := filepath.Join(cosDir, relPath) cosPath := filepath.Join(cosDir, relPath)
cosPath = strings.TrimPrefix(filepath.ToSlash(cosPath), "/")
fileMap[path] = cosPath fileMap[path] = cosPath
} }
@ -181,8 +187,9 @@ func (c *COSUtil) ConcurrentUploadDirectory(localDir, cosDir string, workers int
return fmt.Errorf("计算相对路径失败: %v", err) return fmt.Errorf("计算相对路径失败: %v", err)
} }
// 构造COS路径 // 构造COS路径,确保没有前导斜杠
cosPath := filepath.Join(cosDir, relPath) cosPath := filepath.Join(cosDir, relPath)
cosPath = strings.TrimPrefix(filepath.ToSlash(cosPath), "/")
// 启动goroutine并发上传 // 启动goroutine并发上传
wg.Add(1) wg.Add(1)