Kratos 不支持内置 multipart 文件上传,需手动解析:通过 http.Context.Request() 获取 *http.Request,调用 ParseMultipartForm 和 FormFile 实现文件接收。

Kratos 本身不内置 multipart 文件上传解析能力,HTTP 层默认只处理 JSON/Protobuf 请求体。要支持文件上传(如 multipart/form-data),必须手动接入标准 http.Request 的原始解析逻辑;下载则需手动构造响应头与流式写入。不能依赖 proto 自动生成的 HTTP handler。
如何在 Kratos HTTP 路由中接收 multipart 文件
必须绕过 Kratos 默认的 binding 流程,直接从 http.Context 获取底层 *http.Request,再调用 r.ParseMultipartForm 和 r.FormFile。Kratos 的 http.Context 提供了 Request() 方法获取原生请求对象。
- 务必在 handler 开头调用
r.ParseMultipartForm(32 (例如限制 32MB),否则FormFile会返回http.ErrNotMultipart - 不要在 proto 中定义
bytes file = 1并期望 gRPC-gateway 自动转成 multipart —— 它只支持 JSON 映射,不解析二进制分块 - 若同时需要表单字段(如
fileName、userId),应统一用r.MultipartForm.Value读取,而非尝试绑定 struct - 示例关键片段:
func (g *GreeterService) Upload(ctx http.Context) error { r := ctx.Request() if err := r.ParseMultipartForm(32
为什么不能用 proto + gRPC-gateway 自动生成上传接口
gRPC-gateway 将 HTTP 请求转为 gRPC 调用时,仅支持将请求体反序列化为 proto message(JSON/YAML/FORM URL-encoded),但 multipart/form-data 是多段二进制结构,无法映射到任意 proto 字段。即使你定义了 bytes file,gateway 也只会尝试把整个 raw body 当作 base64 解码,而不是按 boundary 分割提取文件流。
- 错误现象:
proto: can't skip unknown wire type 6或空file字段 - 试图在 proto 中加
option (google.api.http) = { post: "/upload" body: "*" }无效 ——body: "*"仅表示透传原始 body 字节,不触发 multipart 解析 - 结论:涉及文件上传的 endpoint 必须手写 HTTP handler,彻底脱离 proto 自动生成链
如何安全地提供文件下载(流式响应)
下载本质是设置正确响应头 + 逐块写入文件内容。Kratos 的 http.Context 支持 WriteHeader 和 Writer(),但要注意避免一次性加载大文件到内存。
- 必须设置
Content-Disposition: attachment; filename="xxx",否则浏览器可能内嵌渲染而非下载 - 对大文件,用
io.Copy直接从磁盘/MinIO reader 写入ctx.Writer(),禁用gzip中间件(它会缓冲整个响应) - 若文件路径来自用户输入,务必校验路径是否落在允许目录内(防止
../路径遍历),推荐用filepath.Join(allowedRoot, cleanName)+strings.HasPrefix双重检查 - 示例:
func (g *GreeterService) Download(ctx http.Context) error { filename := ctx.PathValue("filename") cleanName := filepath.Base(filename) // 防止路径穿越 path := filepath.Join("/data/uploads", cleanName) f, err := os.Open(path) if err != nil { return errors.NotFound("download.file", "file not found: %s", filename) } defer f.Close() ctx.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, cleanName)) ctx.Header().Set("Content-Type", "application/octet-stream") _, err = io.Copy(ctx.Writer(), f) return err }
真正麻烦的不是代码量,而是 multipart 边界解析的细节(比如空文件、重复字段、超大字段内存占用)、下载时的并发文件句柄泄漏、以及 MinIO 预签名 URL 过期时间与前端上传超时的对齐——这些地方一不留神就会在线上出 500 或连接复位。











