iris.Context.ServeFile 默认不设置 Content-Disposition,浏览器依 MIME 类型决定渲染或下载;需手动设 Header 才能强制下载,MVC 中须在方法内直接调用 ServeFile 且避免混用 JSON/View。

iris.Context.ServeFile 会强制设置 Content-Disposition 吗
不会,ServeFile 默认不设置 Content-Disposition,浏览器通常按 MIME 类型决定是渲染还是下载。比如 .pdf 可能直接在标签页打开,.zip 更可能触发下载——但这不可控,取决于客户端配置和 MIME 推断结果。
要确保下载,必须手动设置 Content-Disposition: attachment。Iris 提供了更直接的 ctx.SendFile 和 ctx.ServeFile 的变体用法,但最稳妥的是组合使用:
ctx.Header("Content-Disposition", "attachment; filename=\"myfile.zip\"")-
ctx.ContentType("application/zip")(可选,但推荐显式指定) ctx.ServeFile("/path/to/file.zip")
用 ctx.SendFile 实现带中文文件名的下载
HTTP 标准不支持 UTF-8 文件名直接写入 Content-Disposition,否则 Chrome/Firefox 可能乱码或截断。Iris 没有内置自动编码,需手动处理。
推荐用 url.PathEscape + filename*=UTF-8'' 格式,例如:
filename := "报告_2024年Q3.xlsx"
encoded := url.PathEscape(filename)
ctx.Header("Content-Disposition", "attachment; filename=\""+filename+"\"; filename*=UTF-8''"+encoded)
注意点:
- 必须同时提供
filename=(ASCII fallback)和filename*=(RFC 5987 兼容格式) -
url.PathEscape是 Go 标准库函数,不是 Iris 特有,需import "net/url" - Windows Edge 旧版可能忽略
filename*,所以 fallback 仍需保留且尽量用 ASCII 字符
大文件下载时 ctx.ServeFile 卡住或内存飙升
ServeFile 底层调用 http.ServeFile,默认使用 io.Copy 流式传输,本身不加载全文件进内存——但如果启用了 Iris 的响应压缩中间件(如 Compress),它会尝试缓冲整个响应体再压缩,导致 OOM。
解决方法:
- 对下载路由禁用压缩:
app.Get("/download", downloadHandler).DisableBodyConsumptionOnUnmarshal(true)(虽不直接影响压缩,但配合下一条更安全) - 显式绕过压缩中间件:用
app.Get("/download", func(ctx iris.Context) { ... }).SkipHandler(iris.Compression)(需确认你注册压缩中间件时用了iris.Compression名字) - 改用
ctx.ServeContent自定义分块读取,控制 buffer 大小(适合需要加校验、限速或日志的场景)
如何在 MVC Controller 中触发文件下载
Iris MVC 的 Controller 方法默认返回值会被 JSON 序列化,不能直接调用 ctx.ServeFile。必须通过 context.Context 原生接口操作响应流。
正确做法是把 iris.Context 注入到方法参数中,并在方法体内直接写响应:
func (c *DownloadController) GetByid(ctx iris.Context) {
id := ctx.Params().Get("id")
path := findFilePathByID(id)
if path == "" {
ctx.StatusCode(404)
ctx.WriteString("not found")
return
}
ctx.Header("Content-Disposition", "attachment; filename=\"data.zip\"")
ctx.ServeFile(path)
}
关键提醒:
- 不要在 MVC 方法里 return 任何结构体或字符串,那会覆盖你已写的响应头和 body
- 如果需要复用逻辑,把文件路径查找、Header 设置等封装成独立函数,但
ServeFile必须在 controller 方法体内调用 - MVC 的依赖注入(如
*iris.Application)在此场景无意义,纯 HTTP 响应操作不需要它
文件下载本质是 HTTP 响应控制,MVC 层只是入口包装,真正起作用的永远是 iris.Context 的原生命令。容易被忽略的是:一旦调用了 ServeFile 或 SendFile,就不要再试图用 ctx.JSON 或 ctx.View,它们会冲突并报错 http: superfluous response.WriteHeader。


















