package logic import ( "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/file" "fusenapi/utils/hash" "time" "context" "fusenapi/server/upload/internal/svc" "fusenapi/server/upload/internal/types" "github.com/zeromicro/go-zero/core/logx" ) type UploadFileBaseLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewUploadFileBaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileBaseLogic { return &UploadFileBaseLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } // 处理进入前逻辑w,r // func (l *UploadFileBaseLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { // } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *UploadFileBaseLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) // } func (l *UploadFileBaseLogic) UploadFileBase(req *types.UploadFileBaseReq, userinfo *auth.UserInfo) (resp *basic.Response) { // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null // 定义用户ID和S3键名格式 var userId int64 var guestId int64 // 检查用户是否是游客 if userinfo != nil { if userinfo.IsGuest() { // 如果是,使用游客ID和游客键名格式 guestId = userinfo.GuestId } else { // 否则,使用用户ID和用户键名格式 userId = userinfo.UserId } if guestId == 0 { guestId = req.GuestId } if userId == 0 { userId = req.UserId } } // 根据hash 查询数据资源 var resourceId string = hash.JsonHashKey(req.FileKey) // 上传文件 var upload = file.Upload{ Ctx: l.ctx, MysqlConn: l.svcCtx.MysqlConn, AwsSession: l.svcCtx.AwsSession, } uploadRes, err := upload.UploadFileByBase64(&file.UploadBaseReq{ FileHash: resourceId, FileData: req.FileData, UploadBucket: req.UploadBucket, ApiType: req.ApiType, UserId: userId, GuestId: guestId, Source: req.Source, Refresh: req.Refresh, Metadata: req.Metadata, ResourceId: req.ResourceId, }) if err != nil { logx.Error(err) return resp.SetStatus(basic.CodeFileUploadErr, "upload file failed") } // 是否备份--异步任务 if req.BackupType != "" { upload.UploadType = "oss" upload.AliyunOSS.Endpoint = l.svcCtx.Config.AliyunOSS.Endpoint upload.AliyunOSS.AccessKeyId = l.svcCtx.Config.AliyunOSS.AccessKeyId upload.AliyunOSS.AccessKeySecret = l.svcCtx.Config.AliyunOSS.AccessKeySecret upload.AliyunOSS.BucketName = l.svcCtx.Config.AliyunOSS.BucketName upload.AliyunOSS.BucketUrl = l.svcCtx.Config.AliyunOSS.BucketUrl upload.AliyunOSS.BasePath = l.svcCtx.Config.AliyunOSS.BasePath time.AfterFunc(time.Second*1, func() { err = upload.UploadFileByUrl(resourceId, uploadRes.ResourceUrl) }) } // 返回成功的响应和上传URL return resp.SetStatus(basic.CodeOK, map[string]interface{}{ "upload_data": UploadUrl{ Status: 1, ResourceId: uploadRes.ResourceId, ResourceUrl: uploadRes.ResourceUrl, }, }) }