亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號