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 关注
- 151 浏览
添加回答
举报