GoFrame 數(shù)據(jù)返回-文件下載

2022-04-14 09:51 更新

?Response?對象支持文件下載。

相關(guān)方法:

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

ServeFile

通過給定文件路徑?path?,?ServeFile?方法將會自動識別文件格式,如果是目錄或者文本內(nèi)容將會直接展示文件內(nèi)容。如果?path?參數(shù)為目錄,那么第二個(gè)參數(shù)?allowIndex?控制是否可以展示目錄下的文件列表。

使用示例:


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 可以發(fā)現(xiàn)文件內(nèi)容被展示到了頁面。

ServeFileDownload

?ServeFileDownload?是相對使用頻率比較高的方法,用于直接引導(dǎo)客戶端下載指定路徑的文件,并可以重新給定下載的文件名稱。?ServeFileDownload?方法采用的是流式下載控制,對內(nèi)存占用較少。使用示例,我們把上面示例中的?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 可以發(fā)現(xiàn)文件被引導(dǎo)下載,而不是展示頁面內(nèi)容。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號