代码拉取完成,页面将自动刷新
package archive
import (
"archive/zip"
"bytes"
"gitee.com/h79/goutils/common/file"
fileconfig "gitee.com/h79/goutils/common/file/config"
"io"
"os"
"path/filepath"
"strings"
)
func IsZip(zipPath string) bool {
f, err := os.Open(zipPath)
if err != nil {
return false
}
defer f.Close()
buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}
return bytes.Equal(buf, []byte("PK\x03\x04"))
}
func UnZipFile(archive, target string, stream ...fileconfig.WriteStream) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
defer reader.Close()
for i := range reader.File {
f := reader.File[i]
path := filepath.Join(target, f.Name)
if f.FileInfo().IsDir() {
if err := os.MkdirAll(path, f.Mode()); err != nil {
return err
}
continue
}
fileReader, err := f.Open()
if err != nil {
return err
}
targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
_ = fileReader.Close()
return err
}
if _, err := io.Copy(targetFile, fileReader); err != nil {
_ = targetFile.Close()
_ = fileReader.Close()
return err
}
for j := range stream {
stream[j].OnWriter(targetFile)
}
_ = targetFile.Close()
_ = fileReader.Close()
}
return nil
}
func ZipFile(srcPath, destPath string, stream ...fileconfig.ReaderStream) error {
zipFile, err := os.Create(destPath)
if err != nil {
return err
}
defer zipFile.Close()
return ZipWrite(zipFile, srcPath, stream...)
}
func ZipWrite(writer io.Writer, srcPath string, stream ...fileconfig.ReaderStream) error {
archive := zip.NewWriter(writer)
defer archive.Close()
depth := file.WithMaxDepth()
return file.ReadDir(srcPath, &depth, func(path string, isDir bool, entry os.DirEntry) int {
info, err := entry.Info()
if err != nil {
return -1
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return -1
}
header.Name = strings.TrimPrefix(path, srcPath+`/`)
if isDir {
header.Name += `/`
} else {
header.Method = zip.Deflate
}
w, err := archive.CreateHeader(header)
if err != nil {
return -1
}
if isDir {
return 0
}
f, err := os.Open(path)
if err != nil {
return -2
}
defer f.Close()
if ll, err := io.Copy(w, f); err != nil || ll != info.Size() {
return -3
}
for i := range stream {
stream[i].OnReader(f)
}
return 0
})
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。