---
title: "数据返回-文件下载"
url: "https://goframe.org/docs/web/response-file-downloading"
markdown_url: "https://goframe.org/docs/web/response-file-downloading.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "WEB 服务开发"
category: "WEB 服务开发 / 数据返回"
published: "2024-10-21"
updated: "2024-11-11"
description: "在使用GoFrame框架构建的应用程序中通过Response对象实现文件下载功能。通过ServeFile方法可以展示文件内容，而通过ServeFileDownload方法则可以引导客户端下载指定路径的文件，充分利用流式下载技术以减少内存占用，提升性能。"
keywords: ["GoFrame", "GoFrame框架", "文件下载", "ServeFile", "ServeFileDownload", "响应文件下载", "Go语言", "ghttp", "服务器", "流式下载"]
---

# 数据返回-文件下载

`Response` 对象支持文件下载。

相关方法：

```go
func (r *Response) ServeFile(path string, allowIndex ...bool)
func (r *Response) ServeFileDownload(path string, name ...string)
```

## `ServeFile`

通过给定文件路径 `path`， `ServeFile` 方法将会自动识别文件格式，如果是目录或者文本内容将会直接展示文件内容。如果 `path` 参数为目录，那么第二个参数 `allowIndex` 控制是否可以展示目录下的文件列表。

使用示例：

![](https://goframe.org/markdown/2bb757548c004e021cf802495fe8d2be.png)

```go
package main

import (
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/net/ghttp"
)

func main() {
    s := g.Server()
    s.BindHandler("/", func(r *ghttp.Request) {
        r.Response.ServeFile("test.txt")
    })
    s.SetPort(8999)
    s.Run()
}
```

访问 [http://127.0.0.1:8999](http://127.0.0.1:8999) 可以发现文件内容被展示到了页面。

## `ServeFileDownload`

`ServeFileDownload` 是相对使用频率比较高的方法，用于直接引导客户端下载指定路径的文件，并可以重新给定下载的文件名称。 `ServeFileDownload` 方法采用的是流式下载控制，对内存占用较少。使用示例，我们把上面示例中的 `ServeFile` 方法改为 `ServeFileDownload` 方法：

```go
package main

import (
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/net/ghttp"
)

func main() {
    s := g.Server()
    s.BindHandler("/", func(r *ghttp.Request) {
        r.Response.ServeFileDownload("test.txt")
    })
    s.SetPort(8999)
    s.Run()
}
```

访问 [http://127.0.0.1:8999](http://127.0.0.1:8999) 可以发现文件被引导下载，而不是展示页面内容。
