fusenapi/server/upload/internal/logic/uploadfilebackendlogic.go
2023-08-10 15:23:28 +08:00

111 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/file"
"fusenapi/utils/hash"
"io"
"net/http"
"context"
"fusenapi/server/upload/internal/svc"
"fusenapi/server/upload/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type UploadFileBackendLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
r *http.Request
}
func NewUploadFileBackendLogic(r *http.Request, svcCtx *svc.ServiceContext) *UploadFileBackendLogic {
return &UploadFileBackendLogic{
Logger: logx.WithContext(r.Context()),
ctx: r.Context(),
svcCtx: svcCtx,
r: r,
}
}
// 处理进入前逻辑w,r
// func (l *UploadFileBackendLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *UploadFileBackendLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *UploadFileBackendLogic) UploadFileBackend(req *types.UploadFileBackendReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
if userinfo.IsOnlooker() {
// 如果是,返回未授权的错误码
return resp.SetStatus(basic.CodeUnAuth)
}
// 定义用户ID和S3键名格式
var userId int64
var guestId int64
// 检查用户是否是游客
if userinfo.IsGuest() {
// 如果是使用游客ID和游客键名格式
guestId = userinfo.GuestId
} else {
// 否则使用用户ID和用户键名格式
userId = userinfo.UserId
}
//设置内存大小
l.r.ParseMultipartForm(32 << 20)
fileObject, _, err := l.r.FormFile("file")
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
// 读取数据流
ioData, err := io.ReadAll(fileObject)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "file upload err,no files")
}
// 上传文件
var upload = file.Upload{
Ctx: l.ctx,
MysqlConn: l.svcCtx.MysqlConn,
AwsSession: l.svcCtx.AwsSession,
}
var resourceId string = hash.JsonHashKey(req.FileKey)
uploadRes, err := upload.UploadFileByByte(&file.UploadBaseReq{
FileHash: resourceId,
FileByte: ioData,
UploadBucket: req.UploadBucket,
ApiType: req.ApiType,
UserId: userId,
GuestId: guestId,
})
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeFileUploadErr, "upload file failed")
}
// 返回成功的响应和上传URL
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"upload_data": UploadUrl{
Status: 1,
ResourceId: uploadRes.ResourceId,
ResourceUrl: uploadRes.ResourceUrl,
},
})
}