GoFrame文件上传需定义/upload接口并用GetUploadFile获取文件;配置SetMaxBodySize设上传大小限制;保存前创建目录、生成唯一文件名,用file.Save安全存储;再通过MIME和file.Size做类型与大小校验。

定义接收文件的上传接口
在 GoFrame 中实现文件上传,首先要明确接口路径、请求方法和参数绑定方式。使用 ghttp.Request 的 GetUploadFile 方法可安全提取 multipart 表单中的文件字段。
在 controller 中编写如下处理函数:
s.BindHandler("/upload", func(r *ghttp.Request) {
file, err := r.GetUploadFile("file")
if err != nil {
r.Response.WriteStatus(400)
r.Response.Write("invalid file field")
return
}
// 后续保存逻辑
})
注意:字段名 【"file"】 必须与前端表单中 的 name 属性完全一致,否则 GetUploadFile 返回空文件和错误。
配置上传大小限制
GoFrame 默认限制单个请求体最大为 8MB,超出即返回 413 Request Entity Too Large 错误。该限制由 HTTP Server 的 MaxBodySize 控制,需在启动服务前显式设置。
方法一:使用 SetConfigWithMap 配置
s := g.Server()
s.SetConfigWithMap(g.Map{
"maxBodySize": 50 * 1024 * 1024 // 单位为字节,此处设为 50MB
})
s.Run()
方法二:调用专用 setter(推荐)
s := g.Server()
s.SetMaxBodySize(50 * 1024 * 1024)
s.Run()
【必须在 s.Run() 之前调用,否则配置不生效】。若未设置且上传文件超过默认 8MB,请求会在进入路由前被拦截,Controller 函数根本不会执行。
保存上传文件到本地目录
第一步:确保目标目录存在且进程有写权限
path := "/var/uploads"
if err := gfile.Mkdir(path); err != nil {
r.Response.WriteStatus(500)
r.Response.Write("upload dir init failed")
return
}
一款AI工具,主要用于Monitor and clean up invalid Codex authentication files in CPA. Check quota status, disable files returning 401 errors, and perform dual verification before deletion.,适合需要提升相关任务效率的用户。
第二步:生成唯一文件名,避免覆盖和注入风险
ext := gfile.Ext(file.Filename)
uniqueName := gtime.Now().TimestampNano() + gconv.String(grand.Intn(99999)) + ext
savePath := gfile.Join(path, uniqueName)
第三步:调用 file.Save 执行保存
if err := file.Save(savePath); err != nil {
r.Response.WriteStatus(500)
r.Response.Write("save failed: " + err.Error())
return
}
这一步会自动校验文件是否为合法上传文件(非恶意路径穿越),file.Save 内部已做防护,无需额外 sanitize 路径。
验证文件类型与大小(业务层校验)
HTTP 层的 MaxBodySize 是全局兜底,但业务常需对单个文件做独立限制,比如头像 ≤ 2MB、PDF 报告 ≤ 10MB。
步骤一:读取文件内存头信息判断 MIME 类型
buf := make([]byte, 512)
n, _ := file.Open().Read(buf)
mimeType := gfile.GetMIME(buf[:n])
if mimeType != "image/jpeg" && mimeType != "image/png" {
r.Response.WriteStatus(400)
r.Response.Write("only jpeg/png allowed")
return
}
步骤二:获取文件真实大小并比对
size := file.Size()
if size > 2*1024*1024 {
r.Response.WriteStatus(400)
r.Response.Write("file too large, max 2MB")
return
}
注意:不要依赖前端传来的 Content-Length 或隐藏字段,file.Size() 返回的是上传时解析出的真实字节数,可靠。










