接口参数调整

This commit is contained in:
ryan
2026-06-11 15:32:44 +08:00
parent ad97ca7df1
commit 6b93320404
10 changed files with 86 additions and 83 deletions
+16 -14
View File
@@ -33,8 +33,7 @@ import (
// @Tags upload
// @Produce octet-stream
// @Param id path string true "文件 ID"
// @Param compress query string false "是否启用压缩 (传任意非空值代表启用,非图片文件将被忽略)"
// @Param level query string false "压缩质量等级 (low, medium, high),默认为 high"
// @Param quality query string false "图片质量 (low, medium, high, origin),默认为 origin"
// @Success 200 {file} file "成功获取文件内容"
// @Failure 400 {object} util.ResponseAny "文件 ID 格式错误"
// @Failure 401 {object} util.ResponseAny "未登录"
@@ -89,22 +88,16 @@ func getUploadRecordByID(c *gin.Context) (*model.Upload, error) {
// ServeUpload 将已存在的文件内容读取并流式响应给客户端,支持本地和 S3/CDN 驱动,并可选支持 WebP 图片压缩与本地缓存。
func ServeUpload(c *gin.Context, upload *model.Upload) {
compressStr := c.Query("compress")
quality := normalizeImageQuality(c.Query("quality"))
isImage := strings.HasPrefix(strings.ToLower(upload.MimeType), "image/") || isImageExtension(strings.ToLower(upload.Extension))
if compressStr == "" || !isImage {
if quality == "origin" || !isImage {
serveOriginal(c, upload)
return
}
// Map level parameter to standard options
level := strings.ToLower(c.Query("level"))
if level != "low" && level != "medium" && level != "high" {
level = "high"
}
cache := diskcache.GetGlobalCache()
cacheKey := imageCompressionCacheKey(upload, level)
cacheKey := imageCompressionCacheKey(upload, quality)
if webpBytes, err := cache.Get(cacheKey); err == nil {
c.Data(http.StatusOK, "image/webp", webpBytes)
return
@@ -121,7 +114,7 @@ func ServeUpload(c *gin.Context, upload *model.Upload) {
}
// Compress to WebP
webpBytes, err := CompressImageToWebP(bytes.NewReader(origBytes), level)
webpBytes, err := CompressImageToWebP(bytes.NewReader(origBytes), quality)
if err != nil {
logger.ErrorF(c.Request.Context(), "failed to compress image to WebP: %v", err)
serveOriginal(c, upload)
@@ -136,17 +129,26 @@ func ServeUpload(c *gin.Context, upload *model.Upload) {
c.Data(http.StatusOK, "image/webp", webpBytes)
}
func imageCompressionCacheKey(upload *model.Upload, level string) string {
func imageCompressionCacheKey(upload *model.Upload, quality string) string {
return fmt.Sprintf(
"upload_webp_v1_%d_%d_%d_%s_%s",
upload.ID,
upload.UpdatedAt.UnixNano(),
upload.FileSize,
upload.Hash,
level,
quality,
)
}
func normalizeImageQuality(quality string) string {
switch strings.ToLower(quality) {
case "low", "medium", "high":
return strings.ToLower(quality)
default:
return "origin"
}
}
// serveOriginal 原始文件的流式响应逻辑
func serveOriginal(c *gin.Context, upload *model.Upload) {
if upload.StorageDriver == "local" || (upload.StorageDriver == "" && !storage.IsEnabled()) {
+33 -7
View File
@@ -279,8 +279,8 @@ func TestImageCompression(t *testing.T) {
}
})
t.Run("serve compressed WebP file with compress=true", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/f/3001?compress=true&level=medium", nil)
t.Run("serve compressed WebP file with medium quality", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/f/3001?quality=medium", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
@@ -320,17 +320,43 @@ func TestImageCompression(t *testing.T) {
}
})
t.Run("serve compressed with default quality high", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/f/3001?compress=true", nil)
t.Run("serve original file with origin quality", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/f/3001?quality=origin", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
cacheKey := imageCompressionCacheKey(&uploadRecord, "high")
if _, err := cache.Get(cacheKey); err != nil {
t.Errorf("disk cache Get(%q) returned error: %v", cacheKey, err)
if w.Header().Get("Content-Type") != "image/png" {
t.Errorf("expected Content-Type image/png, got %s", w.Header().Get("Content-Type"))
}
if !bytes.Equal(w.Body.Bytes(), pngBuf.Bytes()) {
t.Errorf("origin-quality response differs from original image")
}
})
}
func TestNormalizeImageQuality(t *testing.T) {
tests := []struct {
name string
quality string
want string
}{
{name: "low", quality: "low", want: "low"},
{name: "medium", quality: "medium", want: "medium"},
{name: "high", quality: "high", want: "high"},
{name: "origin", quality: "origin", want: "origin"},
{name: "uppercase", quality: "LOW", want: "low"},
{name: "empty", quality: "", want: "origin"},
{name: "invalid", quality: "maximum", want: "origin"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := normalizeImageQuality(tt.quality); got != tt.want {
t.Errorf("normalizeImageQuality(%q) = %q, want %q", tt.quality, got, tt.want)
}
})
}
}
+3 -4
View File
@@ -174,8 +174,7 @@ func UploadFile(c *gin.Context) {
// @Tags upload
// @Produce octet-stream
// @Param id path string true "文件 ID"
// @Param compress query string false "是否启用压缩 (传任意非空值代表启用,非图片文件将被忽略)"
// @Param level query string false "压缩质量等级 (low, medium, high),默认为 high"
// @Param quality query string false "图片质量 (low, medium, high, origin),默认为 origin"
// @Security SessionCookie
// @Success 200 {file} file "成功下载文件"
// @Failure 400 {object} util.ResponseAny "参数错误"
@@ -198,10 +197,10 @@ func DownloadFile(c *gin.Context) {
}
fileName := upload.FileName
compressStr := c.Query("compress")
quality := normalizeImageQuality(c.Query("quality"))
isImage := strings.HasPrefix(strings.ToLower(upload.MimeType), "image/") || isImageExtension(strings.ToLower(upload.Extension))
if compressStr != "" && isImage {
if quality != "origin" && isImage {
ext := filepath.Ext(fileName)
if ext != "" {
fileName = strings.TrimSuffix(fileName, ext) + ".webp"
+9 -9
View File
@@ -43,8 +43,8 @@ func ValidateS3Key(key string) error {
}
// CompressImageToWebP decodes an image from srcReader and encodes it into WebP format
// using the specified quality level (low -> 60, medium -> 75, high -> 85).
func CompressImageToWebP(srcReader io.Reader, qualityLevel string) ([]byte, error) {
// using the specified quality (low -> 60, medium -> 75, high -> 85).
func CompressImageToWebP(srcReader io.Reader, quality string) ([]byte, error) {
// Decode the image
img, format, err := image.Decode(srcReader)
if err != nil {
@@ -52,22 +52,22 @@ func CompressImageToWebP(srcReader io.Reader, qualityLevel string) ([]byte, erro
}
// Determine quality
var quality float32
switch strings.ToLower(qualityLevel) {
var qualityScore float32
switch strings.ToLower(quality) {
case "low":
quality = 60
qualityScore = 60
case "medium":
quality = 75
qualityScore = 75
case "high", "":
quality = 85
qualityScore = 85
default:
quality = 85
qualityScore = 85
}
// Encode to WebP
var buf bytes.Buffer
err = webp.Encode(&buf, img, &webp.EncoderOptions{
Quality: quality,
Quality: qualityScore,
Method: 4, // Default method
})
if err != nil {