文件下载
Gin 提供多种文件下载方式,满足不同场景需求。
基本下载
使用 c.File() 返回文件:
Go
r.GET("/download", func(c *gin.Context) {
c.File("./files/report.pdf")
})
指定下载文件名
使用 c.FileAttachment() 指定保存时的文件名:
Go
r.GET("/download", func(c *gin.Context) {
c.FileAttachment("./files/report.pdf", "报表.pdf")
})
流式下载大文件
适用于大文件,避免内存占用过高:
Go
r.GET("/download/large", func(c *gin.Context) {
file, err := os.Open("./files/large.zip")
if err != nil {
c.String(500, "文件不存在")
return
}
defer file.Close()
// 获取文件信息
fi, _ := file.Stat()
// 设置响应头
c.Header("Content-Disposition", "attachment; filename=large.zip")
c.DataFromReader(200, fi.Size(), "application/zip", file, nil)
})
动态生成文件下载
从内存数据生成文件供下载:
Go
r.GET("/download/csv", func(c *gin.Context) {
data := []byte("id,name,age\n1,张三,25\n2,李四,30")
c.Header("Content-Disposition", "attachment; filename=users.csv")
c.Data(200, "text/csv; charset=utf-8", data)
})
常用响应头
| 响应头 | 说明 |
|---|---|
| Content-Type | 文件 MIME 类型 |
| Content-Disposition | 下载文件名 |
| Content-Length | 文件大小 |
对于大文件下载,优先使用
DataFromReader流式传输,避免内存溢出。
要点总结
c.File()直接返回文件路径c.FileAttachment()可指定下载文件名- 大文件使用
DataFromReader流式传输 - 可通过响应头控制下载行为
📝 发现内容有误?点击此处直接编辑