编辑
2023-10-25
后端
00
请注意,本文编写于 563 天前,最后修改于 563 天前,其中某些信息可能已经过时。
go
package main import ( "archive/zip" "fmt" "github.com/gin-gonic/gin" "io" "net/http" "os" "path/filepath" ) func zipDirectory(directoryPath string, zipFilePath string) error { zipFile, err := os.Create(zipFilePath) if err != nil { return err } defer zipFile.Close() zipWriter := zip.NewWriter(zipFile) defer zipWriter.Close() err = filepath.Walk(directoryPath, func(filePath string, fileInfo os.FileInfo, err error) error { if err != nil { return err } if !fileInfo.Mode().IsRegular() { return nil } relativePath, err := filepath.Rel(directoryPath, filePath) if err != nil { return err } file, err := os.Open(filePath) if err != nil { return err } defer file.Close() zipEntry, err := zipWriter.Create(filepath.ToSlash(relativePath)) if err != nil { return err } _, err = io.Copy(zipEntry, file) return err }) return err } func handleDirectoryDownload(c *gin.Context) { // 要压缩的目录路径 Name := c.Param("filename") directoryPath := fmt.Sprintf("%s/%s", "static", Name) // 创建临时的 ZIP 文件 zipFilePath := fmt.Sprintf("%s.zip", Name) fmt.Println(zipFilePath) err := zipDirectory(directoryPath, zipFilePath) if err != nil { c.String(500, "创建错误!") return } defer os.Remove(zipFilePath) val := fmt.Sprintf("attachment; filename=%s.zip", Name) // 设置响应头,指定文件名和 MIME 类型 //c.Header("Content-Disposition", "attachment; filename=download.zip") c.Header("Content-Disposition", val) c.Header("Content-Type", "application/zip") // 将 ZIP 文件内容写入响应体 http.ServeFile(c.Writer, c.Request, zipFilePath) } func main() { r := gin.Default() r.GET("/download/:filename", handleDirectoryDownload) r.Run(":8080") }

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!