This commit is contained in:
xujiang
2025-07-10 18:09:11 +08:00
parent 5cbdc5af73
commit 604b9e59ba
95 changed files with 23709 additions and 19 deletions

View File

@ -4,11 +4,13 @@ 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"
)
@ -28,13 +30,15 @@ func NewUploadPhotoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Uploa
}
}
func (l *UploadPhotoLogic) UploadPhoto(req *types.UploadPhotoRequest) (resp *types.UploadPhotoResponse, err error) {
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 {
return nil, errors.New("未登录或登录已过期")
// 临时解决方案如果没有用户ID使用默认值1
// 后续需要实现JWT中间件
userId = int64(1)
}
// 2. 验证分类是否存在
@ -43,24 +47,39 @@ func (l *UploadPhotoLogic) UploadPhoto(req *types.UploadPhotoRequest) (resp *typ
return nil, errors.New("分类不存在")
}
// 3. 创建照片记录
// 注意:这里的文件上传和处理需要在 handler 层处理
// 业务逻辑层只处理数据库操作
photo := &model.Photo{
Title: req.Title,
Description: sql.NullString{String: req.Description, Valid: req.Description != ""},
UserId: userId.(int64),
CategoryId: req.CategoryId,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
// 3. 处理文件上传
fileConfig := fileUtil.Config{
MaxSize: l.svcCtx.Config.FileUpload.MaxSize,
UploadDir: l.svcCtx.Config.FileUpload.UploadDir,
AllowedTypes: l.svcCtx.Config.FileUpload.AllowedTypes,
}
_, err = l.svcCtx.PhotoModel.Insert(l.ctx, photo)
uploadResult, err := fileUtil.UploadPhoto(file, header, fileConfig)
if err != nil {
return nil, err
}
// 4. 返回上传结果
// 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,
@ -70,8 +89,8 @@ func (l *UploadPhotoLogic) UploadPhoto(req *types.UploadPhotoRequest) (resp *typ
Id: photo.Id,
Title: photo.Title,
Description: photo.Description.String,
FilePath: photo.FilePath,
ThumbnailPath: photo.ThumbnailPath,
FilePath: uploadResult.Original.URL,
ThumbnailPath: uploadResult.Thumbnail.URL,
UserId: photo.UserId,
CategoryId: photo.CategoryId,
CreatedAt: photo.CreatedAt.Unix(),