1 回答

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()
}
- 1 回答
- 0 關注
- 196 瀏覽
添加回答
舉報