package handler import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" "github.com/wmms/wmms/pkg/response" ) var allowedExts = map[string]bool{ ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true, ".webp": true, } var maxSize int64 = 5 << 20 // 5MB func (h *Handler) UploadImage(c *gin.Context) { file, err := c.FormFile("image") if err != nil { response.BadRequest(c, "请选择要上传的图片") return } if file.Size > maxSize { response.BadRequest(c, "图片大小不能超过5MB") return } ext := strings.ToLower(filepath.Ext(file.Filename)) if !allowedExts[ext] { response.BadRequest(c, "只支持 JPG、PNG、GIF、BMP、WEBP 格式的图片") return } // Generate unique filename filename := fmt.Sprintf("%d_%d%s", time.Now().UnixNano(), time.Now().Unix()%10000, ext) uploadDir := "./uploads" if err := os.MkdirAll(uploadDir, 0755); err != nil { response.InternalError(c, "创建上传目录失败") return } dst := filepath.Join(uploadDir, filename) if err := c.SaveUploadedFile(file, dst); err != nil { response.InternalError(c, "保存文件失败") return } // Return URL path url := "/uploads/" + filename response.Success(c, map[string]string{ "url": url, }) }