From 2f45255e352fd2d6ef71a285700a80d04a52f15d Mon Sep 17 00:00:00 2001 From: ata <17314593+asdxzaaaaa@user.noreply.gitee.com> Date: Fri, 10 Jul 2026 10:06:22 +0000 Subject: [PATCH] Add internal/service/upload.go --- internal/service/upload.go | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 internal/service/upload.go diff --git a/internal/service/upload.go b/internal/service/upload.go new file mode 100644 index 0000000..b08e945 --- /dev/null +++ b/internal/service/upload.go @@ -0,0 +1,54 @@ +package service + +import ( + "fmt" + "io" + "path/filepath" + "time" + + "gotest/internal/config" + "gotest/internal/storage" +) + +// UploadService 文件上传服务 +type UploadService struct { + storage storage.Storage + cfg *config.Config +} + +// NewUploadService 创建上传服务实例 +func NewUploadService(s storage.Storage, cfg *config.Config) *UploadService { + return &UploadService{storage: s, cfg: cfg} +} + +// Upload 上传文件,返回访问 URL +// filename 原始文件名(用于提取扩展名),contentType MIME 类型,fileSize 文件大小(字节),reader 文件内容流 +func (s *UploadService) Upload(filename string, contentType string, fileSize int64, reader io.Reader) (string, error) { + // 校验文件大小 + if fileSize > s.cfg.Upload.MaxSize { + return "", fmt.Errorf("文件大小超过限制(最大 %d 字节)", s.cfg.Upload.MaxSize) + } + + // 校验文件类型 + allowed := false + for _, t := range s.cfg.Upload.AllowedTypes { + if t == contentType { + allowed = true + break + } + } + if !allowed { + return "", fmt.Errorf("不支持的文件类型: %s", contentType) + } + + // 生成存储 key:按日期分目录 + 时间戳文件名 + ext := filepath.Ext(filename) + key := fmt.Sprintf("%s%s", time.Now().Format("2006/01/02/150405.000000"), ext) + + url, err := s.storage.Upload(key, reader, contentType) + if err != nil { + return "", fmt.Errorf("文件上传失败: %w", err) + } + + return url, nil +}