GoFrame 数据返回-文件下载

Response​对象支持文件下载。

相关方法:

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

ServeFile

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

使用示例:

GoFrame 数据返回-文件下载

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 可以发现文件内容被展示到了页面。

ServeFileDownload

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

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 可以发现文件被引导下载,而不是展示页面内容。

作者:terry,如若转载,请注明出处:https://www.web176.com/goframe/20861.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年5月18日
下一篇 2023年5月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注