zipfiles.go 1.4 KB

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