fusenapi/utils/file/upload.go

128 lines
3.1 KiB
Go
Raw Normal View History

package file
import (
"context"
"fusenapi/model/gmodel"
"fusenapi/utils/basic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type Upload struct {
Ctx context.Context
MysqlConn *gorm.DB
AwsSession *session.Session
}
type UploadBaseReq struct {
FileHash string
FileData string
Metadata string
UploadBucket int64
ApiType int64
UserId int64
GuestId int64
}
type UploadBaseRes struct {
Key string `json:"key"`
Status int64 `json:"status"`
ApiType int64 `json:"api_type"`
ResourceId string `json:"resource_id"`
ResourceType string `json:"resource_type"`
ResourceUrl string `json:"resource_url"`
}
func (upload *Upload) UploadFileByBase64(req *UploadBaseReq) (*UploadBaseRes, error) {
// 定义存储桶名称
var bucketName *string
var apiType int64 = req.ApiType
// 根据类别选择存储桶
switch req.UploadBucket {
case 2:
bucketName = basic.TempfileBucketName
default:
bucketName = basic.StorageBucketName
}
// 设置AWS会话的区域
upload.AwsSession.Config.Region = aws.String("us-west-1")
// 创建新的S3服务实例
svc := s3.New(upload.AwsSession)
// 定义S3请求和当前时间
var s3req *request.Request
var resourceId string = req.FileHash
var uploadBaseRes = UploadBaseRes{}
resourceModel := gmodel.NewFsResourceModel(upload.MysqlConn)
resourceInfo, err := resourceModel.FindOneById(upload.Ctx, resourceId)
if err == nil && resourceInfo.ResourceId != "" {
uploadBaseRes.Status = 1
uploadBaseRes.ResourceId = resourceId
uploadBaseRes.ResourceUrl = *resourceInfo.ResourceUrl
} else {
dist, contentType, err := FileBase64ToByte(req.FileData)
if err != nil {
logx.Errorf("err:%+vdesc:%+v", err, "fail.upload.resourceInfoGet.mysql")
return nil, err
}
// 创建S3对象存储请求
s3req, _ = svc.PutObjectRequest(
&s3.PutObjectInput{
Bucket: bucketName,
Key: &resourceId,
},
)
// 设置请求体为文件数据
s3req.SetBufferBody(dist)
// 发送请求
err = s3req.Send()
// 检查是否有错误
if err != nil {
logx.Errorf("err:%+vdesc:%+v", err, "fail.upload.s3req")
return nil, err
} else {
var url = s3req.HTTPRequest.URL.String()
// 打印请求URL
logx.Info(url)
uploadBaseRes.Status = 1
uploadBaseRes.ResourceId = resourceId
uploadBaseRes.ResourceUrl = url
var version string = "0.0.1"
var nowTime = time.Now()
_, err = resourceModel.Create(upload.Ctx, &gmodel.FsResource{
ResourceId: resourceId,
UserId: &req.UserId,
GuestId: &req.GuestId,
ResourceType: &contentType,
ResourceUrl: &url,
Version: &version,
UploadedAt: &nowTime,
Metadata: &req.Metadata,
ApiType: &apiType,
BucketName: bucketName,
})
if err != nil {
logx.Errorf("err:%+vdesc:%+v", err, "fail.upload.resourceInfoAdd.mysql")
return nil, err
}
}
}
return &uploadBaseRes, err
}