1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package utils
- import (
- "archive/zip"
- "io"
- "os"
- "strings"
- )
- //@author: [piexlmax](https://github.com/piexlmax)
- //@function: ZipFiles
- //@description: 压缩文件
- //@param: filename string, files []string, oldform, newform string
- //@return: error
- func ZipFiles(filename string, files []string, oldForm, newForm string) error {
- newZipFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer func() {
- _ = newZipFile.Close()
- }()
- zipWriter := zip.NewWriter(newZipFile)
- defer func() {
- _ = zipWriter.Close()
- }()
- // 把files添加到zip中
- for _, file := range files {
- zipFile, err := os.Open(file)
- if err != nil {
- return err
- }
- err = func() error {
- defer func() {
- _ = zipFile.Close()
- }()
- // 获取file的基础信息
- info, err := zipFile.Stat()
- if err != nil {
- return err
- }
- header, err := zip.FileInfoHeader(info)
- if err != nil {
- return err
- }
- // 使用上面的FileInfoHeader() 就可以把文件保存的路径替换成我们自己想要的了,如下面
- header.Name = strings.Replace(file, oldForm, newForm, -1)
- // 优化压缩
- // 更多参考see http://golang.org/pkg/archive/zip/#pkg-constants
- header.Method = zip.Deflate
- writer, err := zipWriter.CreateHeader(header)
- if err != nil {
- return err
- }
- if _, err = io.Copy(writer, zipFile); err != nil {
- return err
- }
- return nil
- }()
- if err != nil {
- return err
- }
- }
- return nil
- }
|