84 lines
2.0 KiB
Go
84 lines
2.0 KiB
Go
package handler
|
||
|
||
import (
|
||
"gotest/internal/service"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// UploadHandler 文件上传处理器
|
||
type UploadHandler struct {
|
||
uploadService *service.UploadService
|
||
}
|
||
|
||
// NewUploadHandler 创建上传处理器
|
||
func NewUploadHandler(uploadService *service.UploadService) *UploadHandler {
|
||
return &UploadHandler{uploadService: uploadService}
|
||
}
|
||
|
||
// Upload 文件上传 POST /api/v1/upload?module=enterprise
|
||
// module 参数指定上传到哪个模块(enterprise/shop/food/game/app/music/common)
|
||
func (h *UploadHandler) Upload(c *gin.Context) {
|
||
module := c.DefaultQuery("module", "common")
|
||
|
||
file, err := c.FormFile("file")
|
||
if err != nil {
|
||
FailBadRequest(c, "请选择要上传的文件")
|
||
return
|
||
}
|
||
|
||
src, err := file.Open()
|
||
if err != nil {
|
||
FailInternal(c, "文件读取失败")
|
||
return
|
||
}
|
||
defer src.Close()
|
||
|
||
url, err := h.uploadService.Upload(module, file.Filename, file.Header.Get("Content-Type"), file.Size, src)
|
||
if err != nil {
|
||
FailBadRequest(c, err.Error())
|
||
return
|
||
}
|
||
|
||
Success(c, gin.H{"url": url})
|
||
}
|
||
|
||
// ListFiles 文件列表 GET /api/v1/upload/list?module=enterprise
|
||
func (h *UploadHandler) ListFiles(c *gin.Context) {
|
||
module := c.DefaultQuery("module", "common")
|
||
|
||
files, err := h.uploadService.ListFiles(module)
|
||
if err != nil {
|
||
FailInternal(c, "获取文件列表失败: "+err.Error())
|
||
return
|
||
}
|
||
|
||
Success(c, gin.H{
|
||
"list": files,
|
||
"total": len(files),
|
||
})
|
||
}
|
||
|
||
// DeleteFile 删除文件 DELETE /api/v1/upload?module=enterprise&filename=xxx.jpg
|
||
func (h *UploadHandler) DeleteFile(c *gin.Context) {
|
||
module := c.DefaultQuery("module", "common")
|
||
filename := c.Query("filename")
|
||
if filename == "" {
|
||
FailBadRequest(c, "文件名不能为空")
|
||
return
|
||
}
|
||
|
||
if err := h.uploadService.DeleteFile(module, filename); err != nil {
|
||
FailBadRequest(c, "删除失败: "+err.Error())
|
||
return
|
||
}
|
||
|
||
SuccessMsg(c, "删除成功")
|
||
}
|
||
|
||
// GetModules 获取支持的模块列表 GET /api/v1/upload/modules
|
||
func (h *UploadHandler) GetModules(c *gin.Context) {
|
||
modules := h.uploadService.GetModules()
|
||
Success(c, gin.H{"modules": modules})
|
||
}
|