0f3efbc895
MD5 去重本来就有(相同内容直接返回已有记录不重传);对象名从 files/<md5> 改成 uploads/2026-07/<md5>,跨月的同内容仍走去重不重复占用。 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
93 lines
2.6 KiB
Go
93 lines
2.6 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/sundynix/pets-be/internal/model"
|
|
)
|
|
|
|
// 允许的图片扩展名(服务端兜底校验,前端已限制仅图片)
|
|
var imageExts = map[string]bool{
|
|
".jpg": true, ".jpeg": true, ".png": true, ".gif": true,
|
|
".webp": true, ".bmp": true, ".heic": true, ".heif": true,
|
|
}
|
|
|
|
// UploadFile 上传文件并按 MD5 去重:内容相同直接返回已存记录,不重复占用 MinIO 空间。
|
|
func (s *Service) UploadFile(reader io.Reader, filename, contentType string) (*model.File, error) {
|
|
data, err := io.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sum := md5.Sum(data)
|
|
md5hex := hex.EncodeToString(sum[:])
|
|
|
|
// 已有相同内容 → 直接复用(URL 按当前配置重建,避免旧地址)
|
|
var existing model.File
|
|
if err := s.db.Where("md5 = ?", md5hex).First(&existing).Error; err == nil {
|
|
existing.URL = s.storage.PublicURL(existing.ObjectName)
|
|
return &existing, nil
|
|
}
|
|
|
|
ext := strings.ToLower(path.Ext(filename))
|
|
if !imageExts[ext] && !strings.HasPrefix(contentType, "image/") {
|
|
return nil, errors.New("只允许上传图片文件")
|
|
}
|
|
if contentType == "" {
|
|
contentType = "application/octet-stream"
|
|
}
|
|
// 按上传月份分文件夹:uploads/2026-07/<md5>.jpg。文件名仍用 md5 保证唯一。
|
|
// 同内容命中上面的去重直接复用,不会因为跨月再传一份
|
|
objectName := "uploads/" + time.Now().Format("2006-01") + "/" + md5hex + ext
|
|
url, err := s.storage.Upload(objectName, bytes.NewReader(data), int64(len(data)), contentType)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
f := model.File{
|
|
MD5: md5hex, ObjectName: objectName, URL: url,
|
|
Size: int64(len(data)), ContentType: contentType, Ext: ext,
|
|
}
|
|
if err := s.db.Create(&f).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &f, nil
|
|
}
|
|
|
|
// fileURL 按 file_id 取 URL(由 object_name + 当前配置拼出,空 id 或不存在返回空串)
|
|
func (s *Service) fileURL(id string) string {
|
|
if id == "" {
|
|
return ""
|
|
}
|
|
var f model.File
|
|
if err := s.db.Select("object_name").First(&f, "id = ?", id).Error; err != nil {
|
|
return ""
|
|
}
|
|
return s.storage.PublicURL(f.ObjectName)
|
|
}
|
|
|
|
// fileURLs 批量按 file_id 取 URL
|
|
func (s *Service) fileURLs(ids []string) map[string]string {
|
|
out := map[string]string{}
|
|
clean := make([]string, 0, len(ids))
|
|
for _, id := range ids {
|
|
if id != "" {
|
|
clean = append(clean, id)
|
|
}
|
|
}
|
|
if len(clean) == 0 {
|
|
return out
|
|
}
|
|
var files []model.File
|
|
s.db.Select("id, object_name").Where("id IN ?", clean).Find(&files)
|
|
for _, f := range files {
|
|
out[f.ID] = s.storage.PublicURL(f.ObjectName)
|
|
}
|
|
return out
|
|
}
|