package controllers import ( "crypto/md5" "encoding/hex" "encoding/json" "fmt" "strings" "time" "server/models" "server/pkg/identity" "server/pkg/jwtutil" "server/services" beego "github.com/beego/beego/v2/server/web" "github.com/qiniu/go-sdk/v7/auth/qbox" "github.com/qiniu/go-sdk/v7/storage" ) type QiniuUploadController struct { beego.Controller } func (c *QiniuUploadController) platformClaims() (*jwtutil.Claims, error) { return identity.Claims(c.Ctx.Request.Header.Get("Authorization"), identity.EndPlatform) } func (c *QiniuUploadController) effectiveTid(claims *jwtutil.Claims) uint64 { if claims.TenantId > 0 { return uint64(claims.TenantId) } return 0 } func (c *QiniuUploadController) jsonErr(httpStatus, bizCode int, msg string) { c.Ctx.Output.SetStatus(httpStatus) c.Data["json"] = map[string]interface{}{"code": bizCode, "msg": msg} _ = c.ServeJSON() } func (c *QiniuUploadController) jsonOK(data interface{}) { c.Data["json"] = map[string]interface{}{"code": 200, "data": data} _ = c.ServeJSON() } func (c *QiniuUploadController) ParseJSON(v interface{}) error { body := c.Ctx.Input.RequestBody if len(body) == 0 { return fmt.Errorf("请求体为空") } return json.Unmarshal(body, v) } func (c *QiniuUploadController) GetUploadToken() { _, err := c.platformClaims() if err != nil { code := identity.Status(err) c.jsonErr(code, code, err.Error()) return } cfg, err := models.GetStorageConfig() if err != nil || cfg.StorageType != "qiniu" { c.jsonErr(400, 400, "当前未配置七牛云存储") return } if cfg.QiniuAccessKey == "" || cfg.QiniuSecretKey == "" || cfg.QiniuBucket == "" { c.jsonErr(500, 500, "七牛云配置不完整") return } datePath := time.Now().Format("2006/01/02") timestamp := time.Now().UnixNano() keyPrefix := fmt.Sprintf("%s/%s/%d", services.SourcePlatform, datePath, timestamp) mac := qbox.NewMac(cfg.QiniuAccessKey, cfg.QiniuSecretKey) putPolicy := storage.PutPolicy{ Scope: cfg.QiniuBucket, ReturnBody: `{"key":"$(key)","hash":"$(etag)","size":$(fsize),"mimeType":"$(mimeType)"}`, Expires: 3600, } upToken := putPolicy.UploadToken(mac) c.jsonOK(map[string]interface{}{ "token": upToken, "domain": cfg.QiniuDomain, "bucket": cfg.QiniuBucket, "region": cfg.QiniuRegion, "keyPrefix": keyPrefix, "expires": time.Now().Add(time.Hour).Unix(), "uploadUrl": getQiniuUploadURL(cfg.QiniuRegion), }) } func (c *QiniuUploadController) SaveFileRecord() { claims, err := c.platformClaims() if err != nil { code := identity.Status(err) c.jsonErr(code, code, err.Error()) return } tid := c.effectiveTid(claims) body := c.Ctx.Input.RequestBody fmt.Println("SaveFileRecord 请求体长度:", len(body)) fmt.Println("SaveFileRecord 请求体内容:", string(body)) type SaveRequest struct { Key string `json:"key"` Hash string `json:"hash"` Size int64 `json:"size"` Name string `json:"name"` MimeType string `json:"mimeType"` Cate uint64 `json:"cate"` } var req SaveRequest if err := c.ParseJSON(&req); err != nil { c.jsonErr(400, 400, "参数解析失败: "+err.Error()) return } if req.Key == "" || req.Name == "" { c.jsonErr(400, 400, "缺少必填参数") return } cfg, err := models.GetStorageConfig() if err != nil || cfg.StorageType != "qiniu" { c.jsonErr(400, 400, "当前未配置七牛云存储") return } domain := strings.TrimRight(cfg.QiniuDomain, "/") fileURL := fmt.Sprintf("%s/%s", domain, req.Key) md5Sum := req.Hash if md5Sum == "" { h := md5.New() h.Write([]byte(req.Key)) md5Sum = hex.EncodeToString(h.Sum(nil)) } exist, err := services.FindDuplicate(services.SourcePlatform, services.ScopeTenant, tid, 0, md5Sum) if err != nil { c.jsonErr(500, 500, "查重失败: "+err.Error()) return } if exist != nil { c.Data["json"] = map[string]interface{}{ "code": 201, "msg": "文件已存在", "data": map[string]interface{}{ "url": exist.Src, "id": exist.ID, "name": exist.Name, }, } _ = c.ServeJSON() return } id, err := services.CreateFileRecord(services.FileUploadParams{ Source: services.SourcePlatform, Scope: services.ScopeTenant, Tid: tid, Uid: uint64(claims.UserID), Name: req.Name, Ext: getQiniuFileExt(req.Name), Cate: req.Cate, Size: uint64(req.Size), Src: fileURL, ObjectKey: req.Key, Storage: services.StorageTypeQiniu, MD5: md5Sum, }) if err != nil { c.jsonErr(500, 500, "保存文件记录失败: "+err.Error()) return } c.jsonOK(map[string]interface{}{ "url": fileURL, "id": uint64(id), "name": req.Name, "key": req.Key, }) } func (c *QiniuUploadController) GetStorageConfig() { _, err := c.platformClaims() if err != nil { code := identity.Status(err) c.jsonErr(code, code, err.Error()) return } cfg, err := models.GetStorageConfig() if err != nil { c.jsonOK(map[string]interface{}{ "storageType": "local", }) return } c.jsonOK(map[string]interface{}{ "storageType": cfg.StorageType, "qiniuDomain": cfg.QiniuDomain, "qiniuRegion": cfg.QiniuRegion, }) } func getQiniuUploadURL(region string) string { switch region { case "z0": return "https://up-z0.qiniup.com" case "z1": return "https://up-z1.qiniup.com" case "z2": return "https://up-z2.qiniup.com" case "na0": return "https://up-na0.qiniup.com" case "as0": return "https://up-as0.qiniup.com" case "cn-east-2": return "https://up-cn-east-2.qiniup.com" default: return "https://up-z0.qiniup.com" } } func getQiniuFileExt(filename string) string { parts := strings.Split(filename, ".") if len(parts) > 1 { return strings.ToLower(parts[len(parts)-1]) } return "" } func detectQiniuFileType(ext string) uint8 { imageExts := map[string]bool{ "jpg": true, "jpeg": true, "png": true, "gif": true, "bmp": true, "webp": true, "svg": true, "ico": true, } videoExts := map[string]bool{ "mp4": true, "avi": true, "mov": true, "wmv": true, "flv": true, "mkv": true, "webm": true, "m4v": true, } audioExts := map[string]bool{ "mp3": true, "wav": true, "flac": true, "aac": true, "ogg": true, "m4a": true, "wma": true, } docExts := map[string]bool{ "doc": true, "docx": true, "xls": true, "xlsx": true, "ppt": true, "pptx": true, "pdf": true, "txt": true, "md": true, } archiveExts := map[string]bool{ "zip": true, "rar": true, "7z": true, "tar": true, "gz": true, "bz2": true, "xz": true, } executableExts := map[string]bool{ "exe": true, "msi": true, "dmg": true, "pkg": true, "deb": true, "rpm": true, "apk": true, "msix": true, } if imageExts[ext] { return 1 } if videoExts[ext] { return 2 } if audioExts[ext] { return 3 } if docExts[ext] { return 4 } if archiveExts[ext] || executableExts[ext] { return 5 } return 0 }