优化首页分页和图片上传
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
package file
|
||||
|
||||
type UploadDTO struct {
|
||||
ObjectKey string `json:"object_key"`
|
||||
URL string `json:"url"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
URL string `json:"url"`
|
||||
ThumbnailURL string `json:"thumbnail_url,omitempty"`
|
||||
MediumURL string `json:"medium_url,omitempty"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
_ "image/png"
|
||||
"math"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
xdraw "golang.org/x/image/draw"
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
const (
|
||||
ImageVariantThumb = "thumb"
|
||||
ImageVariantMedium = "medium"
|
||||
)
|
||||
|
||||
const (
|
||||
thumbMaxSide = 480
|
||||
mediumMaxSide = 1280
|
||||
)
|
||||
|
||||
type generatedImageVariant struct {
|
||||
Key string
|
||||
Content []byte
|
||||
ContentType string
|
||||
}
|
||||
|
||||
type imageVariantConfig struct {
|
||||
Name string
|
||||
MaxSide int
|
||||
Quality int
|
||||
}
|
||||
|
||||
var imageVariantConfigs = []imageVariantConfig{
|
||||
{Name: ImageVariantThumb, MaxSide: thumbMaxSide, Quality: 76},
|
||||
{Name: ImageVariantMedium, MaxSide: mediumMaxSide, Quality: 82},
|
||||
}
|
||||
|
||||
func ImageVariantKey(key string, variant string) string {
|
||||
ext := path.Ext(key)
|
||||
base := strings.TrimSuffix(key, ext)
|
||||
if base == "" {
|
||||
base = key
|
||||
}
|
||||
return base + "." + variant + ".jpg"
|
||||
}
|
||||
|
||||
func ImageVariantFallbackKeys(key string, variant string) []string {
|
||||
if key == "" {
|
||||
return nil
|
||||
}
|
||||
keys := []string{ImageVariantKey(key, variant)}
|
||||
if strings.HasSuffix(key, ".medium.jpg") && variant == ImageVariantThumb {
|
||||
keys = append(keys, strings.TrimSuffix(key, ".medium.jpg")+"."+ImageVariantThumb+".jpg")
|
||||
}
|
||||
keys = append(keys, key)
|
||||
return dedupeKeys(keys)
|
||||
}
|
||||
|
||||
func generateImageVariants(key string, data []byte, contentType string) []generatedImageVariant {
|
||||
if !strings.HasPrefix(contentType, "image/") || contentType == "image/svg+xml" {
|
||||
return nil
|
||||
}
|
||||
source, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var variants []generatedImageVariant
|
||||
for _, config := range imageVariantConfigs {
|
||||
rendered := resizeForVariant(source, config.MaxSide)
|
||||
encoded, err := encodeJPEG(rendered, config.Quality)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
variants = append(variants, generatedImageVariant{
|
||||
Key: ImageVariantKey(key, config.Name),
|
||||
Content: encoded,
|
||||
ContentType: "image/jpeg",
|
||||
})
|
||||
}
|
||||
return variants
|
||||
}
|
||||
|
||||
func resizeForVariant(source image.Image, maxSide int) image.Image {
|
||||
bounds := source.Bounds()
|
||||
width := bounds.Dx()
|
||||
height := bounds.Dy()
|
||||
if width <= 0 || height <= 0 || maxSide <= 0 {
|
||||
return source
|
||||
}
|
||||
scale := math.Min(float64(maxSide)/float64(width), float64(maxSide)/float64(height))
|
||||
if scale > 1 {
|
||||
scale = 1
|
||||
}
|
||||
targetWidth := max(1, int(math.Round(float64(width)*scale)))
|
||||
targetHeight := max(1, int(math.Round(float64(height)*scale)))
|
||||
target := image.NewRGBA(image.Rect(0, 0, targetWidth, targetHeight))
|
||||
draw.Draw(target, target.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
xdraw.ApproxBiLinear.Scale(target, target.Bounds(), source, bounds, draw.Over, nil)
|
||||
return target
|
||||
}
|
||||
|
||||
func encodeJPEG(source image.Image, quality int) ([]byte, error) {
|
||||
var buffer bytes.Buffer
|
||||
err := jpeg.Encode(&buffer, source, &jpeg.Options{Quality: quality})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buffer.Bytes(), nil
|
||||
}
|
||||
|
||||
func dedupeKeys(keys []string) []string {
|
||||
seen := make(map[string]struct{}, len(keys))
|
||||
result := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
result = append(result, key)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
@@ -34,32 +37,78 @@ func (s *Service) Upload(req uploadRequest) (*UploadDTO, error) {
|
||||
if s.storage == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if req.Header == nil || req.Reader == nil || req.Header.Size <= 0 || req.Header.Size > maxUploadSize {
|
||||
if req.Header == nil || req.Reader == nil || req.Header.Size <= 0 {
|
||||
return nil, ErrInvalidFile
|
||||
}
|
||||
contentType := req.ContentType
|
||||
if contentType == "" {
|
||||
contentType = req.Header.Header.Get("Content-Type")
|
||||
data, err := readUploadData(req.Reader)
|
||||
if err != nil || len(data) == 0 || len(data) > maxUploadSize {
|
||||
return nil, ErrInvalidFile
|
||||
}
|
||||
contentType := normalizeContentType(req.ContentType, data)
|
||||
scene := normalizeScene(req.Scene)
|
||||
if !allowedContentTypes[contentType] || (scene == "chat" && !strings.HasPrefix(contentType, "image/")) {
|
||||
return nil, ErrInvalidFile
|
||||
}
|
||||
key, err := s.storage.Put(req.Context, scene, req.Header, req.Reader, contentType)
|
||||
key, err := newObjectKey(scene, req.Header.Filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.storage.PutObject(req.Context, key, bytes.NewReader(data), int64(len(data)), contentType, map[string]string{
|
||||
"original-filename": req.Header.Filename,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var thumbnailURL string
|
||||
var mediumURL string
|
||||
for _, variant := range generateImageVariants(key, data, contentType) {
|
||||
err := s.storage.PutObject(req.Context, variant.Key, bytes.NewReader(variant.Content), int64(len(variant.Content)), variant.ContentType, map[string]string{
|
||||
"source-object": key,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(variant.Key, "."+ImageVariantThumb+".") {
|
||||
thumbnailURL = fileURLForScene(scene, variant.Key)
|
||||
}
|
||||
if strings.Contains(variant.Key, "."+ImageVariantMedium+".") {
|
||||
mediumURL = fileURLForScene(scene, variant.Key)
|
||||
}
|
||||
}
|
||||
fileURL := fileURLForScene(scene, key)
|
||||
return &UploadDTO{
|
||||
ObjectKey: key,
|
||||
URL: fileURL,
|
||||
ThumbnailURL: thumbnailURL,
|
||||
MediumURL: mediumURL,
|
||||
Filename: req.Header.Filename,
|
||||
ContentType: contentType,
|
||||
Size: int64(len(data)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readUploadData(reader multipart.File) ([]byte, error) {
|
||||
limited := io.LimitReader(reader, maxUploadSize+1)
|
||||
return io.ReadAll(limited)
|
||||
}
|
||||
|
||||
func normalizeContentType(contentType string, data []byte) string {
|
||||
contentType = strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
|
||||
if allowedContentTypes[contentType] {
|
||||
return contentType
|
||||
}
|
||||
detected := strings.ToLower(strings.TrimSpace(strings.Split(http.DetectContentType(data), ";")[0]))
|
||||
if allowedContentTypes[detected] {
|
||||
return detected
|
||||
}
|
||||
return contentType
|
||||
}
|
||||
|
||||
func fileURLForScene(scene string, key string) string {
|
||||
fileURL := "/api/files/object?key=" + url.QueryEscape(key)
|
||||
if scene == "home-banner" || scene == "avatar" {
|
||||
fileURL = "/api/public/files/object?key=" + url.QueryEscape(key)
|
||||
}
|
||||
return &UploadDTO{
|
||||
ObjectKey: key,
|
||||
URL: fileURL,
|
||||
Filename: req.Header.Filename,
|
||||
ContentType: contentType,
|
||||
Size: req.Header.Size,
|
||||
}, nil
|
||||
return fileURL
|
||||
}
|
||||
|
||||
func normalizeScene(scene string) string {
|
||||
|
||||
@@ -53,18 +53,22 @@ func (s *Storage) Put(ctx context.Context, scene string, header *multipart.FileH
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = s.client.PutObject(ctx, s.bucket, key, reader, header.Size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
UserMetadata: map[string]string{
|
||||
"original-filename": header.Filename,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
if err := s.PutObject(ctx, key, reader, header.Size, contentType, map[string]string{
|
||||
"original-filename": header.Filename,
|
||||
}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func (s *Storage) PutObject(ctx context.Context, key string, reader io.Reader, size int64, contentType string, metadata map[string]string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, reader, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
UserMetadata: metadata,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Storage) Get(ctx context.Context, key string) (*Object, error) {
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user