我基本上想在 Golang 中实现这些命令:
cd somedir ; zip -r ../zipped.zip . * ; cd ..
Run Code Online (Sandbox Code Playgroud)
我试图在不包含父目录的情况下压缩父目录中的文件夹和文件。这个帖子是类似的:
https://askubuntu.com/questions/521011/zip-an-archive-without-including-parent-directory
“我如何在 Golang 中递归压缩”
像这样的东西...
package rzip
import (
"archive/zip"
"io"
"os"
"path/filepath"
"strings"
)
func RecursiveZip(pathToZip, destinationPath string) error {
destinationFile, err := os.Create(destinationPath)
if err != nil {
return err
}
myZip := zip.NewWriter(destinationFile)
err = filepath.Walk(pathToZip, func(filePath string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if err != nil {
return err
}
relPath := strings.TrimPrefix(filePath, filepath.Dir(pathToZip))
zipFile, err := myZip.Create(relPath)
if err != nil {
return err
}
fsFile, err := os.Open(filePath)
if err != nil {
return err
}
_, err = io.Copy(zipFile, fsFile)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
err = myZip.Close()
if err != nil {
return err
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
至于 docx 文件和您的实现的问题,如果无法看到您的代码,就很难看出问题是什么。
编辑:
要使用同一目录中的所有文件创建 zip,您只需要更改您在存档中创建的文件的路径。
relPath := strings.TrimPrefix(filePath, filepath.Dir(pathToZip))
zipFile, err := myZip.Create(relPath)
Run Code Online (Sandbox Code Playgroud)
成为
flatPath := filepath.Base(pathToZip)
zipFile, err := myZip.Create(flatPath)
Run Code Online (Sandbox Code Playgroud)
保持目录结构,但省略根目录
relPath := strings.TrimPrefix(filePath, pathToZip)
zipFile, err := myZip.Create(relPath)
Run Code Online (Sandbox Code Playgroud)
干杯,
标记