This commit is contained in:
2026-05-28 14:43:13 +08:00
parent c16a8dfbc4
commit 957a594a0f
7 changed files with 353 additions and 64 deletions
+7 -8
View File
@@ -9,6 +9,8 @@ import (
"path/filepath"
"strings"
"simple_portal/config"
"github.com/disintegration/imaging"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
@@ -24,9 +26,6 @@ var allowedMIMETypes = map[string]string{
// maxUploadSize is the maximum allowed file size in bytes (5 MB).
const maxUploadSize = 5 << 20
// uploadDir is the directory where uploaded files are stored.
const uploadDir = "./data/uploads"
// thumbSuffix is the suffix appended to compressed image filenames.
const thumbSuffix = "_thumb"
@@ -94,13 +93,13 @@ func UploadHandler(c *gin.Context) {
filename := fileUUID + ext
// Ensure upload directory exists
if err := os.MkdirAll(uploadDir, 0755); err != nil {
if err := os.MkdirAll(config.GetUploadDir(), 0755); err != nil {
c.JSON(500, gin.H{"error": "创建上传目录失败"})
return
}
// Save original file
originalPath := filepath.Join(uploadDir, filename)
originalPath := filepath.Join(config.GetUploadDir(), filename)
dst, err := os.Create(originalPath)
if err != nil {
c.JSON(500, gin.H{"error": "保存文件失败"})
@@ -142,14 +141,14 @@ func ServeUploadHandler(c *gin.Context) {
return
}
filePath := filepath.Join(uploadDir, filename)
filePath := filepath.Join(config.GetUploadDir(), filename)
// Check if thumb=1 query parameter is requested
if c.Query("thumb") == "1" {
// Try to serve the thumbnail version
ext := filepath.Ext(filename)
baseName := filename[:len(filename)-len(ext)]
thumbPath := filepath.Join(uploadDir, baseName+thumbSuffix+".jpg")
thumbPath := filepath.Join(config.GetUploadDir(), baseName+thumbSuffix+".jpg")
if _, err := os.Stat(thumbPath); err == nil {
c.File(thumbPath)
@@ -221,7 +220,7 @@ func generateThumbnail(originalPath, fileUUID, uploadType string) error {
thumb := fitImage(img, maxWidth, maxHeight)
// Save thumbnail as JPEG
thumbPath := filepath.Join(uploadDir, fileUUID+thumbSuffix+".jpg")
thumbPath := filepath.Join(config.GetUploadDir(), fileUUID+thumbSuffix+".jpg")
thumbFile, err := os.Create(thumbPath)
if err != nil {
return fmt.Errorf("failed to create thumbnail file: %w", err)