最近遇到了一个下载动态html报表的需要,须要以提供压缩包的模式实现下载性能,实现的过程中发现相干文档十分杂,故总结一下本人的实现。
开发环境:
零碎环境:MacOS + Chrome
框架:beego
压缩性能:tar + gzip
指标压缩文件:自带数据和全部包的动态html文件


    首先先提一下http server文件下载的实现,其实就是在后端返回前端的数据包中,将数据头设置为下载文件的格局,这样前端收到返回的响应时,会间接触发下载性能(就像时平时咱们在chrome中点击下载那样)

数据头设置格局如下:

func (c *Controller)Download() {    //...文件信息的产生逻辑    //    //rw为responseWriter    rw := c.Ctx.ResponseWriter    //规定下载后的文件名    rw.Header().Set("Content-Disposition", "attachment; filename="+"(文件名字)")    rw.Header().Set("Content-Description", "File Transfer")    //表明传输文件类型    //如果是其余类型,请参照: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是一个bytes.Buffer,则需调用b.Bytes()    http.ServeContent(rw, c.Ctx.Request, "(文件名字)", time.Now(), bytes.NewReader(b.Bytes()))}



    这样,beego后端就会将在头部标记为下载文件的数据包发送给前端,前端收到后会主动启动下载性能。

    然而这只是最初一步的状况,如何将咱们的文件先进行压缩再发送给前端提供下载呢?

    如果须要下载的不只一个文件,须要用tar打包,再用gzip进行压缩,实现如下:

    //最内层用bytes.Buffer来进行文件的存储    var b bytes.Buffer    //嵌套tar包的writter和gzip包的writer    gw := gzip.NewWriter(&b)    tw := tar.NewWriter(gw)    dataFile := //...文件的产生逻辑,dataFile为File类型    info, _ := dataFile.Stat()    header, _ := tar.FileInfoHeader(info, "")    //下载后以后文件的门路设置    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())    }    //...能够持续增加文件    //tar writer 和 gzip writer的敞开程序肯定不能反    tw.Close()    gw.Close()



    最初和两头步骤实现了,咱们只剩File文件的产生逻辑了,因为是动态html文件,咱们须要把所有html援用的依赖包全副残缺的写入到生成的文件中的<script>和<style>标签下。此外,在本例子中,报告局部还须要一些动态的json数据来填充表格和图像,这部分数据是以map存储在内存中的。当然能够先保留成文件再进行下面一步的打包压缩,然而这样会产生并发的问题,因而咱们须要先将所有的依赖包文件和数据写入一个byte.Buffer中,最初将这个byte.Buffer转回File格局。

Golang中并没有写好的byte.Buffer转文件的函数能够用,于是咱们须要本人实现。

实现如下:

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 allfunc (mif myFileInfo) ModTime() time.Time { return time.Time{} } // Return whatever you wantfunc (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 dofunc (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}



依赖包和数据的写入逻辑:

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数据写入html    var b bytes.Buffer    // 创立Json编码器    encoder := json.NewEncoder(&b)    err = encoder.Encode(data)    if err != nil {        utils.LogErrorln(err.Error())    }        // 将json数据增加到html模版中    // 形式为在html模版中插入一个非凡的替换字段,本例中为{Data_Json_Source}    html = bytes.Replace(html, []byte("{Data_Json_Source}"), b.Bytes(), 1)    // 将动态文件增加进html    // 如果是.css,则前后减少<style></style>标签    // 如果是.js,则前后减少<script><script>标签    allStaticFiles := make([][]byte, 0)    // jquery 须要最先进行增加    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>"))    //剩下的所有动态文件    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()    }        // 转成http.File格局进行返回    mf := &MyFile{        Reader: bytes.NewReader(html),        mif: myFileInfo{            name: "report.html",            data: html,        },    }    var f http.File = mf    return f}



OK! 目前为止,后端的文件生成->打包->压缩都曾经做好啦,咱们把他们串起来:

func (c *Controller)Download() {    var b bytes.Buffer    gw := gzip.NewWriter(&b)    tw := tar.NewWriter(gw)    // 生成动静report,并增加进压缩包    // 调用上文中的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()))}


    后端局部曾经全副实现了,前端局部如何接管呢,本例中我做了一个按钮嵌套<a>标签来进行申请:
<a href="/traffic/download_indicator?task_id={{$.taskId}}&task_type={{$.taskType}}&status={{$.status}}&agent_addr={{$.agentAddr}}&glaucus_addr={{$.glaucusAddr}}">     <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">下载报表</button></a>



这样,以后端页面中点击下载报表按钮之后,会主动启动下载,下载咱们后端传回的report.tar.gz文件。