This commit is contained in:
2023-09-06 16:20:05 +08:00
parent 11712d856b
commit f4af5d2c21
3 changed files with 59 additions and 1 deletions

View File

@@ -528,3 +528,60 @@ func ZipOneFile(srcFile, dstZip string, pathFlag bool) error {
}
return nil
}
func ZipDirectoryFile(srcDir, dstZip string, pathFlag bool) error {
// Create a new zip file
zipfileWriter, err := os.Create(dstZip)
if err != nil {
return err
}
defer zipfileWriter.Close()
// Create a new zip archive
zipWriter := zip.NewWriter(zipfileWriter)
defer zipWriter.Close()
// Walk through the directory and add files to the zip archive
err = filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Create a new file header for the current file
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
// Set the name of the file within the zip archive
header.Name = filepath.Join(filepath.Base(srcDir), path[len(srcDir):])
// If the current file is a directory, skip it
if info.IsDir() {
return nil
}
// Create a new file in the zip archive
fileWriter, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
// Open the current file
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
// Copy the contents of the current file to the zip archive
_, err = io.Copy(fileWriter, file)
if err != nil {
return err
}
return nil
})
return err
}