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

用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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀