MarketingSystemDataExportTool/server/internal/exporter/util.go

50 lines
1002 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package exporter
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
)
// ZipFiles 将分片文件打包为zip并返回路径与大小同时清理源xlsx分片文件
func ZipFiles(jobID uint64, files []string) (string, int64) {
baseDir := "storage/export"
_ = os.MkdirAll(baseDir, 0755)
zipPath := filepath.Join(baseDir, fmt.Sprintf("job_%d_%d.zip", jobID, time.Now().Unix()))
zf, err := os.Create(zipPath)
if err != nil {
return zipPath, 0
}
defer zf.Close()
zw := zip.NewWriter(zf)
for _, p := range files {
f, err := os.Open(p)
if err != nil {
continue
}
w, err := zw.Create(filepath.Base(p))
if err != nil {
f.Close()
continue
}
_, _ = io.Copy(w, f)
f.Close()
}
_ = zw.Close()
st, err := os.Stat(zipPath)
if err != nil {
return zipPath, 0
}
// 清理xlsx分片文件以节省空间
for _, fp := range files {
if strings.HasSuffix(strings.ToLower(fp), ".xlsx") {
_ = os.Remove(fp)
}
}
return zipPath, st.Size()
}