The Response object supports file downloading.

Related methods:

  1. func (r *Response) ServeFile(path string, allowIndex ...bool)
  2. func (r *Response) ServeFileDownload(path string, name ...string)

ServeFile

With the given file path path, the ServeFile method will automatically recognize the file format. If it’s a directory or text content, it will directly display the file content. If the path parameter is a directory, then the second parameter allowIndex controls whether the file list under the directory can be displayed.

Example usage:

Response - File Downloading - 图1

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. r.Response.ServeFile("test.txt")
  10. })
  11. s.SetPort(8999)
  12. s.Run()
  13. }

Visit http://127.0.0.1:8999 to see that the file content is displayed on the page.

ServeFileDownload

ServeFileDownload is a relatively frequently used method for directly guiding the client to download a file from a specified path and can assign a new name for the downloaded file. The ServeFileDownload method uses streaming download control, which has low memory usage. In the example below, we modify the ServeFile method from the above example to the ServeFileDownload method:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. r.Response.ServeFileDownload("test.txt")
  10. })
  11. s.SetPort(8999)
  12. s.Run()
  13. }

Visit http://127.0.0.1:8999 to see that the file is guided to download rather than displaying the page content.