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 }