You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
1.5 KiB
81 lines
1.5 KiB
package util
|
|
|
|
import (
|
|
"archive/zip"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"xtcfs/config"
|
|
)
|
|
|
|
/*
|
|
* add file to zip
|
|
*/
|
|
func ZipFiles(zipname string, files []string, zippath string) error {
|
|
fmt.Printf("zipname:%s\n", zipname)
|
|
// 创建zip文件
|
|
newZipFile, err := os.Create(zipname)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer newZipFile.Close()
|
|
// zip写头
|
|
zipWriter := zip.NewWriter(newZipFile)
|
|
defer zipWriter.Close()
|
|
|
|
// 把files添加到zip中
|
|
for _, file := range files {
|
|
//
|
|
fmt.Printf("zipfiles in function :%s\n", file)
|
|
|
|
//
|
|
zipfile, err := os.Open(file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer zipfile.Close()
|
|
|
|
//
|
|
info, err := zipfile.Stat()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
//
|
|
header, err := zip.FileInfoHeader(info)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 在zip存档中设置文件的相对路径
|
|
header.Name, err = filepath.Rel(filepath.Dir(config.G.FilePath), file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// 转换为Unix风格的路径分隔符
|
|
header.Name = filepath.ToSlash(header.Name)
|
|
// 目录需要拼上一个 "/" ,否则会出现一个和目录一样的文件在压缩包中
|
|
if info.IsDir() {
|
|
header.Name += "/"
|
|
} else {
|
|
// 将压缩方法设置为deflate
|
|
header.Method = zip.Deflate
|
|
}
|
|
//
|
|
fmt.Printf("header.name is %s\n", header.Name)
|
|
|
|
writer, err := zipWriter.CreateHeader(header)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err = io.Copy(writer, zipfile); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 调用:
|
|
// ZipFiles(zipFileName, files, ".", ".")
|
|
|