全部学科
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 流式传输
  • 可通过响应头控制下载行为
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 错误处理与状态码
下一篇 → 结构体标签
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码