73 lines
2.2 KiB
Go
73 lines
2.2 KiB
Go
package upload
|
||
|
||
import (
|
||
"fmt"
|
||
"mime/multipart"
|
||
"time"
|
||
|
||
"git.echol.cn/loser/ai_wanjia/global"
|
||
)
|
||
|
||
// 平台来源常量
|
||
const (
|
||
SourceApp = "app" // 用户端(app + web)
|
||
SourceCreator = "creator" // 创作者平台
|
||
SourceAdmin = "admin" // 管理后台
|
||
SourceSystem = "system" // 系统/通用(无来源标识时使用)
|
||
)
|
||
|
||
// UploadContext 标识文件上传的来源平台及操作用户
|
||
type UploadContext struct {
|
||
Source string // 平台来源:app / creator / admin / system
|
||
UserID uint // 上传者ID,0 表示无特定用户(系统级操作)
|
||
}
|
||
|
||
// SubDir 生成存储子目录
|
||
// 有用户ID:{source}/{userId}/{date} 例如 app/42/2024-01-15
|
||
// 无用户ID:{source}/{date} 例如 system/2024-01-15
|
||
func (ctx UploadContext) SubDir() string {
|
||
date := time.Now().Format("2006-01-02")
|
||
if ctx.Source == "" {
|
||
ctx.Source = SourceSystem
|
||
}
|
||
if ctx.UserID > 0 {
|
||
return fmt.Sprintf("%s/%d/%s", ctx.Source, ctx.UserID, date)
|
||
}
|
||
return fmt.Sprintf("%s/%s", ctx.Source, date)
|
||
}
|
||
|
||
// OSS 对象存储接口
|
||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||
// Author [ccfish86](https://github.com/ccfish86)
|
||
type OSS interface {
|
||
UploadFile(file *multipart.FileHeader, ctx UploadContext) (string, string, error)
|
||
DeleteFile(key string) error
|
||
}
|
||
|
||
// NewOss OSS的实例化方法
|
||
// Author [SliverHorn](https://github.com/SliverHorn)
|
||
// Author [ccfish86](https://github.com/ccfish86)
|
||
func NewOss() OSS {
|
||
switch global.GVA_CONFIG.System.OssType {
|
||
case "local":
|
||
return &Local{}
|
||
case "qiniu":
|
||
return &Qiniu{}
|
||
case "tencent-cos":
|
||
return &TencentCOS{}
|
||
case "aliyun-oss":
|
||
return &AliyunOSS{}
|
||
case "huawei-obs":
|
||
return HuaWeiObs
|
||
case "minio":
|
||
minioClient, err := GetMinio(global.GVA_CONFIG.Minio.Endpoint, global.GVA_CONFIG.Minio.AccessKeyId, global.GVA_CONFIG.Minio.AccessKeySecret, global.GVA_CONFIG.Minio.BucketName, global.GVA_CONFIG.Minio.UseSSL)
|
||
if err != nil {
|
||
global.GVA_LOG.Warn("你配置了使用minio,但是初始化失败,请检查minio可用性或安全配置: " + err.Error())
|
||
panic("minio初始化失败") // 建议这样做,用户自己配置了minio,如果报错了还要把服务开起来,使用起来也很危险
|
||
}
|
||
return minioClient
|
||
default:
|
||
return &Local{}
|
||
}
|
||
}
|