bindbox-game/internal/api/common/upload_wangeditor.go

76 lines
2.4 KiB
Go
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package common
import (
"net/http"
"strings"
"bindbox-game/internal/code"
"bindbox-game/internal/pkg/core"
)
// @Summary WangEditor图片上传
// @Description 适配 WangEditor 的图片上传接口
// @Tags Common
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "图片文件"
// @Success 200 {object} map[string]any "上传成功"
// @Failure 400 {object} map[string]any "上传失败"
// @Router /common/upload/wangeditor [post]
func (h *handler) UploadWangEditorImage() core.HandlerFunc {
return func(ctx core.Context) {
fh, err := ctx.FormFile("file")
if err != nil {
ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "缺少文件"))
return
}
// 限制文件大小不超过 5MB
if fh.Size > 5*1024*1024 {
ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, "图片大小不能超过5MB"))
return
}
f, err := fh.Open()
if err != nil {
ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, err.Error()))
return
}
defer f.Close()
ct := fh.Header.Get("Content-Type")
if ct == "" {
ct = "application/octet-stream"
}
// 校验图片类型
allowed := map[string]struct{}{
"image/jpeg": {},
"image/jpg": {},
"image/png": {},
"image/gif": {},
"image/webp": {},
"image/bmp": {},
}
if ct == "application/octet-stream" {
// 一些浏览器可能未设置 content-type允许继续服务端会按扩展名纠正
} else if _, ok := allowed[strings.ToLower(ct)]; !ok {
if !strings.HasPrefix(strings.ToLower(ct), "image/") {
ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, "仅支持上传图片类型"))
return
}
}
url, err := h.svc.UploadImage(ctx.RequestContext(), fh.Filename, f, ct)
if err != nil {
ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, err.Error()))
return
}
resp := map[string]any{
"errno": 0,
"data": map[string]string{
"url": url,
},
}
ctx.Payload(resp)
}
}