最近遇到了一個(gè)下載靜態(tài)html報(bào)表的需求,需要以提供壓縮包的形式完成下載功能,實(shí)現(xiàn)的過程中發(fā)現(xiàn)相關(guān)文檔非常雜,故總結(jié)一下自己的實(shí)現(xiàn)。
開發(fā)環(huán)境:
系統(tǒng)環(huán)境:MacOS + Chrome
框架:beego
壓縮功能:tar + gzip
目標(biāo)壓縮文件:自帶數(shù)據(jù)和全部包的靜態(tài)html文件
首先先提一下http server文件下載的實(shí)現(xiàn),其實(shí)就是在后端返回前端的數(shù)據(jù)包中,將數(shù)據(jù)頭設(shè)置為下載文件的格式,這樣前端收到返回的響應(yīng)時(shí),會(huì)直接觸發(fā)下載功能(就像時(shí)平時(shí)我們?cè)赾hrome中點(diǎn)擊下載那樣)
數(shù)據(jù)頭設(shè)置格式如下:
func (c *Controller)Download() {
//...文件信息的產(chǎn)生邏輯
//
//rw為responseWriter
rw := c.Ctx.ResponseWriter
//規(guī)定下載后的文件名
rw.Header().Set("Content-Disposition", "attachment; filename="+"(文件名字)")
rw.Header().Set("Content-Description", "File Transfer")
//標(biāo)明傳輸文件類型
//如果是其他類型,請(qǐng)參照:https://www.runoob.com/http/http-content-type.html
rw.Header().Set("Content-Type", "application/octet-stream")
rw.Header().Set("Content-Transfer-Encoding", "binary")
rw.Header().Set("Expires", "0")
rw.Header().Set("Cache-Control", "must-revalidate")
rw.Header().Set("Pragma", "public")
rw.WriteHeader(http.StatusOK)
//文件的傳輸是用byte slice類型,本例子中:b是一個(gè)bytes.Buffer,則需調(diào)用b.Bytes()
http.ServeContent(rw, c.Ctx.Request, "(文件名字)", time.Now(), bytes.NewReader(b.Bytes()))
}
這樣,beego后端就會(huì)將在頭部標(biāo)記為下載文件的數(shù)據(jù)包發(fā)送給前端,前端收到后會(huì)自動(dòng)啟動(dòng)下載功能。
然而這只是最后一步的情況,如何將我們的文件先進(jìn)行壓縮再發(fā)送給前端提供下載呢?
如果需要下載的不只一個(gè)文件,需要用tar打包,再用gzip進(jìn)行壓縮,實(shí)現(xiàn)如下:
//最內(nèi)層用bytes.Buffer來進(jìn)行文件的存儲(chǔ)
var b bytes.Buffer
//嵌套tar包的writter和gzip包的writer
gw := gzip.NewWriter(b)
tw := tar.NewWriter(gw)
dataFile := //...文件的產(chǎn)生邏輯,dataFile為File類型
info, _ := dataFile.Stat()
header, _ := tar.FileInfoHeader(info, "")
//下載后當(dāng)前文件的路徑設(shè)置
header.Name = "report" + "/" + header.Name
err := tw.WriteHeader(header)
if err != nil {
utils.LogErrorln(err.Error())
return
}
_, err = io.Copy(tw, dataFile)
if err != nil {
utils.LogErrorln(err.Error())
}
//...可以繼續(xù)添加文件
//tar writer 和 gzip writer的關(guān)閉順序一定不能反
tw.Close()
gw.Close()
最后和中間步驟完成了,我們只剩File文件的產(chǎn)生邏輯了,由于是靜態(tài)html文件,我們需要把所有html引用的依賴包全部完整的寫入到生成的文件中的script>和style>標(biāo)簽下。此外,在本例子中,報(bào)告部分還需要一些靜態(tài)的json數(shù)據(jù)來填充表格和圖像,這部分?jǐn)?shù)據(jù)是以map存儲(chǔ)在內(nèi)存中的。當(dāng)然可以先保存成文件再進(jìn)行上面一步的打包壓縮,但是這樣會(huì)產(chǎn)生并發(fā)的問題,因此我們需要先將所有的依賴包文件和數(shù)據(jù)寫入一個(gè)byte.Buffer中,最后將這個(gè)byte.Buffer轉(zhuǎn)回File格式。
Golang中并沒有寫好的byte.Buffer轉(zhuǎn)文件的函數(shù)可以用,于是我們需要自己實(shí)現(xiàn)。
實(shí)現(xiàn)如下:
type myFileInfo struct {
name string
data []byte
}
func (mif myFileInfo) Name() string { return mif.name }
func (mif myFileInfo) Size() int64 { return int64(len(mif.data)) }
func (mif myFileInfo) Mode() os.FileMode { return 0444 } // Read for all
func (mif myFileInfo) ModTime() time.Time { return time.Time{} } // Return whatever you want
func (mif myFileInfo) IsDir() bool { return false }
func (mif myFileInfo) Sys() interface{} { return nil }
type MyFile struct {
*bytes.Reader
mif myFileInfo
}
func (mf *MyFile) Close() error { return nil } // Noop, nothing to do
func (mf *MyFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil // We are not a directory but a single file
}
func (mf *MyFile) Stat() (os.FileInfo, error) {
return mf.mif, nil
}
依賴包和數(shù)據(jù)的寫入邏輯:
func testWrite(data map[string]interface{}, taskId string) http.File {
//最后生成的html,打開html模版
tempfileP, _ := os.Open("views/traffic/generatePage.html")
info, _ := tempfileP.Stat()
html := make([]byte, info.Size())
_, err := tempfileP.Read(html)
// 將data數(shù)據(jù)寫入html
var b bytes.Buffer
// 創(chuàng)建Json編碼器
encoder := json.NewEncoder(b)
err = encoder.Encode(data)
if err != nil {
utils.LogErrorln(err.Error())
}
// 將json數(shù)據(jù)添加到html模版中
// 方式為在html模版中插入一個(gè)特殊的替換字段,本例中為{Data_Json_Source}
html = bytes.Replace(html, []byte("{Data_Json_Source}"), b.Bytes(), 1)
// 將靜態(tài)文件添加進(jìn)html
// 如果是.css,則前后增加style>/style>標(biāo)簽
// 如果是.js,則前后增加script>script>標(biāo)簽
allStaticFiles := make([][]byte, 0)
// jquery 需要最先進(jìn)行添加
tempfilename := "static/report/jquery.min.js"
tempfileP, _ = os.Open(tempfilename)
info, _ = os.Stat(tempfilename)
curFileByte := make([]byte, info.Size())
_, err = tempfileP.Read(curFileByte)
allStaticFiles = append(allStaticFiles, []byte("script>"))
allStaticFiles = append(allStaticFiles, curFileByte)
allStaticFiles = append(allStaticFiles, []byte("/script>"))
//剩下的所有靜態(tài)文件
staticFiles, _ := ioutil.ReadDir("static/report/")
for _, tempfile := range staticFiles {
if tempfile.Name() == "jquery.min.js" {
continue
}
tempfilename := "static/report/" + tempfile.Name()
tempfileP, _ := os.Open(tempfilename)
info, _ := os.Stat(tempfilename)
curFileByte := make([]byte, info.Size())
_, err := tempfileP.Read(curFileByte)
if err != nil {
utils.LogErrorln(err.Error())
}
if isJs, _ := regexp.MatchString(`\.js$`, tempfilename); isJs {
allStaticFiles = append(allStaticFiles, []byte("script>"))
allStaticFiles = append(allStaticFiles, curFileByte)
allStaticFiles = append(allStaticFiles, []byte("/script>"))
} else if isCss, _ := regexp.MatchString(`\.css$`, tempfilename); isCss {
allStaticFiles = append(allStaticFiles, []byte("style>"))
allStaticFiles = append(allStaticFiles, curFileByte)
allStaticFiles = append(allStaticFiles, []byte("/style>"))
}
tempfileP.Close()
}
// 轉(zhuǎn)成http.File格式進(jìn)行返回
mf := MyFile{
Reader: bytes.NewReader(html),
mif: myFileInfo{
name: "report.html",
data: html,
},
}
var f http.File = mf
return f
}
OK! 目前為止,后端的文件生成->打包->壓縮都已經(jīng)做好啦,我們把他們串起來:
func (c *Controller)Download() {
var b bytes.Buffer
gw := gzip.NewWriter(b)
tw := tar.NewWriter(gw)
// 生成動(dòng)態(tài)report,并添加進(jìn)壓縮包
// 調(diào)用上文中的testWrite方法
dataFile := testWrite(responseByRules, strTaskId)
info, _ := dataFile.Stat()
header, _ := tar.FileInfoHeader(info, "")
header.Name = "report_" + strTaskId + "/" + header.Name
err := tw.WriteHeader(header)
if err != nil {
utils.LogErrorln(err.Error())
return
}
_, err = io.Copy(tw, dataFile)
if err != nil {
utils.LogErrorln(err.Error())
}
tw.Close()
gw.Close()
rw := c.Ctx.ResponseWriter
rw.Header().Set("Content-Disposition", "attachment; filename="+"report_"+strTaskId+".tar.gz")
rw.Header().Set("Content-Description", "File Transfer")
rw.Header().Set("Content-Type", "application/octet-stream")
rw.Header().Set("Content-Transfer-Encoding", "binary")
rw.Header().Set("Expires", "0")
rw.Header().Set("Cache-Control", "must-revalidate")
rw.Header().Set("Pragma", "public")
rw.WriteHeader(http.StatusOK)
http.ServeContent(rw, c.Ctx.Request, "report_"+strTaskId+".tar.gz", time.Now(), bytes.NewReader(b.Bytes()))
}
后端部分已經(jīng)全部實(shí)現(xiàn)了,前端部分如何接收呢,本例中我做了一個(gè)按鈕嵌套a>標(biāo)簽來進(jìn)行請(qǐng)求:
a href="/traffic/download_indicator?task_id={{$.taskId}}task_type={{$.taskType}}status={{$.status}}agent_addr={{$.agentAddr}}glaucus_addr={{$.glaucusAddr}}" rel="external nofollow" >
button style="font-family: 'SimHei';font-size: 14px;font-weight: bold;color: #0d6aad;text-decoration: underline;margin-left: 40px;" type="button" class="btn btn-link">下載報(bào)表/button>
/a>
這樣,當(dāng)前端頁面中點(diǎn)擊下載報(bào)表按鈕之后,會(huì)自動(dòng)啟動(dòng)下載,下載我們后端傳回的report.tar.gz文件。
到此這篇關(guān)于Golang實(shí)現(xiàn)http server提供壓縮文件下載功能的文章就介紹到這了,更多相關(guān)Golang http server 壓縮下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- [Asp.Net Core]用Blazor Server Side實(shí)現(xiàn)圖片驗(yàn)證碼
- [Asp.Net Core] 淺談Blazor Server Side
- Ant Design Blazor 組件庫的路由復(fù)用多標(biāo)簽頁功能
- HTTP中header頭部信息詳解
- Golang簡單實(shí)現(xiàn)http的server端和client端
- IOS利用CocoaHttpServer搭建手機(jī)本地服務(wù)器
- 在Golang中使用http.FileServer返回靜態(tài)文件的操作
- 基于http.server搭建局域網(wǎng)服務(wù)器過程解析
- golang的httpserver優(yōu)雅重啟方法詳解
- Blazor Server 應(yīng)用程序中進(jìn)行 HTTP 請(qǐng)求