github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/util/archive/zip.go (about)

     1  package archive
     2  
     3  import (
     4  	"archive/zip"
     5  	"bytes"
     6  	"compress/flate"
     7  	"io"
     8  )
     9  
    10  // ZipWrite 压缩成zip
    11  func ZipWrite(files []*File) (buf *bytes.Buffer, err error) {
    12  	buf = new(bytes.Buffer)
    13  
    14  	// 初始化writer
    15  	w := zip.NewWriter(buf)
    16  	defer w.Close()
    17  
    18  	// 设置压缩级别,不指定则默认
    19  	w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
    20  		return flate.NewWriter(out, flate.BestCompression)
    21  	})
    22  
    23  	var f io.Writer
    24  	for _, file := range files {
    25  
    26  		// 根据文件名称,writer创建文件
    27  		f, err = w.Create(file.Name)
    28  		if err != nil {
    29  			return nil, err
    30  		}
    31  		// 创建的文件写入内容
    32  		if _, err = f.Write(file.Body); err != nil {
    33  			return nil, err
    34  		}
    35  	}
    36  	return
    37  }
    38  
    39  // ZipRead 读取zip压缩文件
    40  func ZipRead(path string) ([]*File, error) {
    41  
    42  	// 根据文件路径,获取zip文件内容
    43  	r, err := zip.OpenReader(path)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	// 方法最后调用关闭
    48  	defer r.Close()
    49  
    50  	// 循环读取多个文件内容
    51  	var rc io.ReadCloser
    52  	var b []byte
    53  	var files []*File
    54  	for _, f := range r.File {
    55  		if err = func(f *zip.File) error {
    56  			// 打开文件
    57  			rc, err = f.Open()
    58  			if err != nil {
    59  				return err
    60  			}
    61  			defer rc.Close()
    62  
    63  			// 读取文件内容
    64  			b, err = io.ReadAll(rc)
    65  			if err != nil {
    66  				return err
    67  			}
    68  			files = append(files, &File{
    69  				Name: f.Name,
    70  				Body: b,
    71  			})
    72  			return nil
    73  		}(f); err != nil {
    74  			return nil, err
    75  		}
    76  	}
    77  	return files, nil
    78  }