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