|
- package svc
-
- import (
- "context"
- "errors"
- "fmt"
- "gim/internal/business/comm/md"
- "gim/internal/business/comm/service/qiniu"
- "gim/internal/business/comm/utils"
- "gim/internal/business/comm/utils/logx"
- "strings"
- )
-
- // 请求文件上传
- func FileReqUpload(ctx context.Context, uid, dirName, fName, callbackUrl string, fSize int64) (interface{}, error) {
- ext := utils.FileExt(fName)
- if err := initStg(ctx, fSize, ext); err != nil {
- return nil, err
- }
- newName := dirName + "_" + fmt.Sprintf("%010s", uid)
-
- // 默认都加时间戳
- newName += "_" + utils.FormatNanoUnix() + utils.RandString(4, "0123456789")
- newName += "." + ext
-
- f := &md.FileCallback{
- Uid: uid,
- DirId: md.FileUserDir[dirName],
- FileName: newName,
- }
- return qiniu.ReqImgUpload(f, callbackUrl), nil
- }
-
- func initStg(ctx context.Context, fSize int64, ext string) error {
- // 获取上传配置
- stgInfo := SysCfgFind(
- ctx,
- md.KEY_CFG_FILE_BUCKET,
- md.KEY_CFG_FILE_HOST,
- md.KEY_CFG_FILE_AK,
- md.KEY_CFG_FILE_SK,
- md.KEY_CFG_FILE_PVD,
- md.KEY_CFG_FILE_REGION,
- md.KEY_CFG_FILE_MAX_SIZE,
- md.KEY_CFG_FILE_EXT,
- md.KEY_CFG_FILE_SCHEME,
- )
-
- if stgInfo == nil {
- return errors.New("获取配置信息出错")
- }
- // todo 目前仅支持七牛
- if v, ok := stgInfo[md.KEY_CFG_FILE_PVD]; !ok || v != "qiniu" {
- return errors.New("file_provider error")
- }
- if v, ok := stgInfo[md.KEY_CFG_FILE_REGION]; !ok || v == "" {
- return errors.New("file_bucket_region error")
- }
- if v, ok := stgInfo[md.KEY_CFG_FILE_AK]; !ok || v == "" {
- return errors.New("file_access_key error")
- }
- if v, ok := stgInfo[md.KEY_CFG_FILE_SK]; !ok || v == "" {
- return errors.New("file_secret_key error")
- }
- if v, ok := stgInfo[md.KEY_CFG_FILE_BUCKET]; !ok || v == "" {
- return errors.New("file_bucket error")
- }
- if v, ok := stgInfo[md.KEY_CFG_FILE_SCHEME]; !ok || v == "" {
- stgInfo[md.KEY_CFG_FILE_SCHEME] = "http"
- SysCfgSet(ctx, md.KEY_CFG_FILE_SCHEME, stgInfo[md.KEY_CFG_FILE_SCHEME], "文件域名HTTP协议")
- }
- qiniu.Init(stgInfo[md.KEY_CFG_FILE_AK], stgInfo[md.KEY_CFG_FILE_SK], stgInfo[md.KEY_CFG_FILE_BUCKET], stgInfo[md.KEY_CFG_FILE_REGION], stgInfo[md.KEY_CFG_FILE_SCHEME])
- if v, ok := stgInfo[md.KEY_CFG_FILE_HOST]; !ok || v == "" {
- var err error
- stgInfo[md.KEY_CFG_FILE_HOST], err = qiniu.BucketGetDomain(stgInfo[md.KEY_CFG_FILE_BUCKET])
- if err != nil {
- logx.Error(err)
- return errors.New("服务器配置错误")
- }
- SysCfgSet(ctx, md.KEY_CFG_FILE_HOST, stgInfo[md.KEY_CFG_FILE_HOST], "文件域名地址")
- }
-
- // 检查文件大小限制
- if v, ok := stgInfo[md.KEY_CFG_FILE_MAX_SIZE]; ok && v != "" && utils.StrToInt64(v) < fSize {
- return errors.New("file_user_upload_max_size error")
- }
- // 检查文件后缀
- if v, ok := stgInfo[md.KEY_CFG_FILE_EXT]; ok && v != "" && !strings.Contains(v, ext) {
- return errors.New("file_ext error")
- }
- return nil
- }
|