bba6dc6b4f
- Replaced common upload handler and service with Qiniu-specific implementations in main.go and route registration. - Deleted outdated upload_handler.go and qiniu_service.go files to streamline the codebase. - Updated route definitions to utilize the new Qiniu upload handler for improved file upload management.
51 lines
1.5 KiB
Go
51 lines
1.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
qiniuservice "wx_service/internal/common/qiniu/service"
|
|
"wx_service/internal/middleware"
|
|
"wx_service/internal/model"
|
|
)
|
|
|
|
type UploadHandler struct {
|
|
qiniuService *qiniuservice.QiniuService
|
|
}
|
|
|
|
func NewUploadHandler(qiniuService *qiniuservice.QiniuService) *UploadHandler {
|
|
return &UploadHandler{qiniuService: qiniuService}
|
|
}
|
|
|
|
type qiniuTokenRequest struct {
|
|
// filename 用于保留文件后缀(可选),例如:"a.png"、"video.mp4"
|
|
Filename string `json:"filename"`
|
|
}
|
|
|
|
// QiniuToken 返回七牛直传所需的 token/key/upload_url 等信息。
|
|
// 建议放在鉴权后:用当前登录用户生成 key,避免前端写入任意路径。
|
|
func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
|
user, ok := middleware.CurrentUser(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
|
return
|
|
}
|
|
|
|
var req qiniuTokenRequest
|
|
_ = c.ShouldBindJSON(&req) // filename 可选,解析失败也不影响生成 token
|
|
|
|
token, err := h.qiniuService.CreateUploadToken(user.MiniProgramID, user.ID, req.Filename)
|
|
if err != nil {
|
|
if errors.Is(err, qiniuservice.ErrQiniuNotConfigured) {
|
|
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置七牛上传服务,请联系管理员"))
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取上传凭证失败,请稍后重试"))
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, model.Success(token))
|
|
}
|