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.

63 lines
1.3 KiB

  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 newZipFile.Close()
  19. zipWriter := zip.NewWriter(newZipFile)
  20. defer zipWriter.Close()
  21. // 把files添加到zip中
  22. for _, file := range files {
  23. zipfile, err := os.Open(file)
  24. if err != nil {
  25. return err
  26. }
  27. defer zipfile.Close()
  28. // 获取file的基础信息
  29. info, err := zipfile.Stat()
  30. if err != nil {
  31. return err
  32. }
  33. header, err := zip.FileInfoHeader(info)
  34. if err != nil {
  35. return err
  36. }
  37. // 使用上面的FileInforHeader() 就可以把文件保存的路径替换成我们自己想要的了,如下面
  38. header.Name = strings.Replace(file, oldform, newform, -1)
  39. // 优化压缩
  40. // 更多参考see http://golang.org/pkg/archive/zip/#pkg-constants
  41. header.Method = zip.Deflate
  42. writer, err := zipWriter.CreateHeader(header)
  43. if err != nil {
  44. return err
  45. }
  46. if _, err = io.Copy(writer, zipfile); err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }