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.

57 lines
1.1 KiB

  1. package utils
  2. import (
  3. "archive/zip"
  4. "io"
  5. "os"
  6. "strings"
  7. )
  8. func ZipFiles(filename string, files []string, oldform, newform string) error {
  9. newZipFile, err := os.Create(filename)
  10. if err != nil {
  11. return err
  12. }
  13. defer newZipFile.Close()
  14. zipWriter := zip.NewWriter(newZipFile)
  15. defer zipWriter.Close()
  16. // 把files添加到zip中
  17. for _, file := range files {
  18. zipfile, err := os.Open(file)
  19. if err != nil {
  20. return err
  21. }
  22. defer zipfile.Close()
  23. // 获取file的基础信息
  24. info, err := zipfile.Stat()
  25. if err != nil {
  26. return err
  27. }
  28. header, err := zip.FileInfoHeader(info)
  29. if err != nil {
  30. return err
  31. }
  32. // 使用上面的FileInforHeader() 就可以把文件保存的路径替换成我们自己想要的了,如下面
  33. header.Name = strings.Replace(file, oldform, newform, -1)
  34. // 优化压缩
  35. // 更多参考see http://golang.org/pkg/archive/zip/#pkg-constants
  36. header.Method = zip.Deflate
  37. writer, err := zipWriter.CreateHeader(header)
  38. if err != nil {
  39. return err
  40. }
  41. if _, err = io.Copy(writer, zipfile); err != nil {
  42. return err
  43. }
  44. }
  45. return nil
  46. }