douba05167
2018-09-19 17:48
浏览 153
已采纳

用golang压缩文件的文件夹会创建损坏的zip

how do I zip files in a folder with sub-directories correctly.

I have a local folder with following structure:

folder/hello/
folder/hello/world/
folder/hello/world/helloword.txt
folder/index.txt

this is my code:

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
    "path/filepath"
)

func main() {

    files, err := listFiles("./folder")
    if err != nil {
        panic(err)
    }

    zipMe(files, "test.zip")

    for _, f := range files {
        fmt.Println(f)
    }
    fmt.Println("Done!")
}

func listFiles(root string) ([]string, error) {
    var files []string

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        files = append(files, path)
        return nil
    })
    if err != nil {
        return nil, err
    }
    return files, nil

}

func zipMe(filepaths []string, target string) error {

    flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
    file, err := os.OpenFile(target, flags, 0644)

    if err != nil {
        return fmt.Errorf("Failed to open zip for writing: %s", err)
    }
    defer file.Close()

    zipw := zip.NewWriter(file)
    defer zipw.Close()

    for _, filename := range filepaths {
        if err := addFileToZip(filename, zipw); err != nil {
            return fmt.Errorf("Failed to add file %s to zip: %s", filename, err)
        }
    }
    return nil

}

func addFileToZip(filename string, zipw *zip.Writer) error {
    file, err := os.Open(filename)

    if err != nil {
        return fmt.Errorf("Error opening file %s: %s", filename, err)
    }
    defer file.Close()

    wr, err := zipw.Create(filename)
    if err != nil {

        return fmt.Errorf("Error adding file; '%s' to zip : %s", filename, err)
    }

    if _, err := io.Copy(wr, file); err != nil {
        return fmt.Errorf("Error writing %s to zip: %s", filename, err)
    }

    return nil
}

This creates a broken zip which can not be extracted (I am running on mac os but this should not make a difference). I also tried several other examples from stackoverflow and links found through google, but I do always get a broken zip. I get a zip with 135 bytes when I extract it I get 1 binary file with 0 bytes).

It would be great if someone could help me to find out what I am missing here.

Thx

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshanji3102 2018-09-19 18:20
    已采纳

    You need to list and zip the files, not the directories. Simply make this adjustment to ignore directories in your listFiles function.

    if !info.IsDir() {
        files = append(files, path)
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题