Files
photography/backend/internal/logic/photo/uploadPhotoLogic.go
xujiang 010fe2a8c7
Some checks failed
部署后端服务 / 🧪 测试后端 (push) Failing after 5m8s
部署后端服务 / 🚀 构建并部署 (push) Has been skipped
部署后端服务 / 🔄 回滚部署 (push) Has been skipped
fix
2025-07-10 18:09:11 +08:00

101 lines
2.7 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 photo
import (
"context"
"database/sql"
"errors"
"mime/multipart"
"time"
"photography-backend/internal/model"
"photography-backend/internal/svc"
"photography-backend/internal/types"
fileUtil "photography-backend/pkg/utils/file"
"github.com/zeromicro/go-zero/core/logx"
)
type UploadPhotoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 上传照片
func NewUploadPhotoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadPhotoLogic {
return &UploadPhotoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UploadPhotoLogic) UploadPhoto(req *types.UploadPhotoRequest, file multipart.File, header *multipart.FileHeader) (resp *types.UploadPhotoResponse, err error) {
// 1. 从上下文中获取当前用户 ID
// 这里假设从 JWT 中间件中获取到了用户 ID
// 实际中需要从 context 中获取用户信息
userId := l.ctx.Value("userId")
if userId == nil {
// 临时解决方案如果没有用户ID使用默认值1
// 后续需要实现JWT中间件
userId = int64(1)
}
// 2. 验证分类是否存在
_, err = l.svcCtx.CategoryModel.FindOne(l.ctx, req.CategoryId)
if err != nil {
return nil, errors.New("分类不存在")
}
// 3. 处理文件上传
fileConfig := fileUtil.Config{
MaxSize: l.svcCtx.Config.FileUpload.MaxSize,
UploadDir: l.svcCtx.Config.FileUpload.UploadDir,
AllowedTypes: l.svcCtx.Config.FileUpload.AllowedTypes,
}
uploadResult, err := fileUtil.UploadPhoto(file, header, fileConfig)
if err != nil {
return nil, err
}
// 4. 创建照片记录
photo := &model.Photo{
Title: req.Title,
Description: sql.NullString{String: req.Description, Valid: req.Description != ""},
FilePath: uploadResult.Original.FilePath,
ThumbnailPath: uploadResult.Thumbnail.FilePath,
UserId: userId.(int64),
CategoryId: req.CategoryId,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err = l.svcCtx.PhotoModel.Insert(l.ctx, photo)
if err != nil {
// 如果数据库保存失败,删除已上传的文件
fileUtil.DeleteFile(uploadResult.Original.FilePath)
fileUtil.DeleteFile(uploadResult.Thumbnail.FilePath)
return nil, err
}
// 5. 返回上传结果
return &types.UploadPhotoResponse{
BaseResponse: types.BaseResponse{
Code: 200,
Message: "上传成功",
},
Data: types.Photo{
Id: photo.Id,
Title: photo.Title,
Description: photo.Description.String,
FilePath: uploadResult.Original.URL,
ThumbnailPath: uploadResult.Thumbnail.URL,
UserId: photo.UserId,
CategoryId: photo.CategoryId,
CreatedAt: photo.CreatedAt.Unix(),
UpdatedAt: photo.UpdatedAt.Unix(),
},
}, nil
}