全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 6 分钟 ✍️ juanwangdev

文件下载

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 流式传输
  • 可通过响应头控制下载行为

📝 发现内容有误?点击此处直接编辑

← 上一篇 响应处理基础
下一篇 → 重定向
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库