为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Gin 在 HTTP 服务器中即时生成 zip / 7z 存档?

如何使用 Gin 在 HTTP 服务器中即时生成 zip / 7z 存档?

Go
慕婉清6462132 2023-07-10 16:42:31
我使用Gin创建一个 HTTP 服务器,我想向用户提供一个动态生成的 zip 存档。理论上,我可以首先在文件系统上生成一个 zip 文件,然后提供它。但这确实是一个糟糕的方法(在开始下载之前等待 5 分钟)。我想立即开始将其提供给用户并在生成内容时推送内容。我找到了 DataFromReader ,但在存档完成之前不知道 ContentLength。func DownloadEndpoint(c *gin.Context) {    ...    c.DataFromReader(        http.StatusOK,        ContentLength,        ContentType,        Body,        map[string]string{            "Content-Disposition": "attachment; filename=\"archive.zip\""),        },    )}我怎样才能做到这一点?
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

使用流方法和archive/zip,您可以动态创建 zip 并将它们流式传输到服务器。

package main


import (

    "os"


    "archive/zip"


    "github.com/gin-gonic/gin"

)


func main() {


    r := gin.Default()

    r.GET("/", func(c *gin.Context) {


        c.Writer.Header().Set("Content-type", "application/octet-stream")

        c.Stream(func(w io.Writer) bool {


            // Create a zip archive.

            ar := zip.NewWriter(w)


            file1, _ := os.Open("filename1")

            file2, _ := os.Open("filename2")

            c.Writer.Header().Set("Content-Disposition", "attachment; filename='filename.zip'")


            f1, _ := ar.Create("filename1")

            io.Copy(f1, file1)

            f2, _ := ar.Create("filename2")

            io.Copy(f2, file2)


            ar.Close()


            return false

        })

    })

    r.Run()

}

直接使用 ResponseWriter


package main


import (

    "io"

    "os"


    "archive/zip"


    "github.com/gin-gonic/gin"

)



func main() {


    r := gin.Default()

    r.GET("/", func(c *gin.Context) {

        c.Writer.Header().Set("Content-type", "application/octet-stream")

        c.Writer.Header().Set("Content-Disposition", "attachment; filename='filename.zip'")

        ar :=  zip.NewWriter(c.Writer)

        file1, _ := os.Open("filename1")

        file2, _ := os.Open("filename2")

        f1, _ := ar.Create("filename1")

        io.Copy(f1, file1)

        f2, _ := ar.Create("filename1")

        io.Copy(f1, file2)

        ar.Close()

    })

    r.Run()

}


查看完整回答
反对 回复 2023-07-10
  • 1 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信