Files
st-react/server/service/app/upload.go
Echo f4e166c5ee 🎉 初始化项目
Signed-off-by: Echo <1711788888@qq.com>
2026-02-27 21:52:00 +08:00

50 lines
1.2 KiB
Go
Raw Permalink 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 app
import (
"errors"
"mime/multipart"
"strings"
"git.echol.cn/loser/st/server/global"
"git.echol.cn/loser/st/server/utils/upload"
"go.uber.org/zap"
)
type UploadService struct{}
// UploadImage 上传图片到 OSS
// 返回图片的访问 URL
func (s *UploadService) UploadImage(header *multipart.FileHeader) (string, error) {
// 验证文件类型
if !isImageFile(header.Filename) {
return "", errors.New("只支持图片格式jpg, jpeg, png, gif, webp")
}
// 验证文件大小(限制 10MB
if header.Size > 10*1024*1024 {
return "", errors.New("图片大小不能超过 10MB")
}
// 使用 OSS 上传
oss := upload.NewOss()
filePath, _, uploadErr := oss.UploadFile(header)
if uploadErr != nil {
global.GVA_LOG.Error("图片上传失败", zap.Error(uploadErr))
return "", errors.New("图片上传失败")
}
return filePath, nil
}
// isImageFile 检查是否为图片文件
func isImageFile(filename string) bool {
ext := strings.ToLower(filename[strings.LastIndex(filename, ".")+1:])
imageExts := []string{"jpg", "jpeg", "png", "gif", "webp"}
for _, validExt := range imageExts {
if ext == validExt {
return true
}
}
return false
}