duanhao8540
2015-02-14 07:26
浏览 550
已采纳

如何使用Golang将文件添加到现有的zip文件中

We can create a zip new file and add files using Go Language.

But, how to add a new file with existing zip file using GoLang?

If we can use Create function, how to get the zip.writer reference?

Bit confused.

图片转代码服务由CSDN问答提供 功能建议

我们可以创建一个zip新文件并使用Go语言添加文件。

但是,如何使用GoLang使用现有的zip文件添加新文件?

如果我们可以使用Create函数,如何获取zip.writer参考? \ n

有点困惑。

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

2条回答 默认 最新

  • dounao4179 2015-02-18 10:57
    已采纳

    After more analysis, i found that, it is not possible to add any files with the existing zip file.

    But, I was able to add files with tar file by following the hack given in this URL.

    打赏 评论
  • duanrenzou1619 2018-09-18 21:16

    Although I have not attempted this yet with a zip file that already exists and then writing to it, I believe you should be able to add files to it.

    This is code I have written to create a conglomerate zip file containing multiple files in order to expedite uploading the data to another location. I hope it helps!

    type fileData struct {
        Filename string
        Body     []byte
    }
    
    func main() {
        outputFilename := "path/to/file.zip"
    
        // whatever you want as filenames and bodies
        fileDatas := createFileDatas()
    
        // create zip file
        conglomerateZip, err := os.Create(outputFilename)
        if err != nil {
            return err
        }
        defer conglomerateZip.Close()
    
        zipWriter := zip.NewWriter(conglomerateZip)
        defer zipWriter.Close()
    
        // populate zip file with multiple files
        err = populateZipfile(zipWriter, fileDatas)
        if err != nil {
            return err
        }
    
    }
    
    func populateZipfile(w *zip.Writer, fileDatas []*fileData) error {
        for _, fd := range fileDatas {
            f, err := w.Create(fd.Filename)
            if err != nil {
                return err
            }
    
            _, err = f.Write([]byte(fd.Body))
            if err != nil {
                return err
            }
    
            err = w.Flush()
            if err != nil {
                return err
            }
        }
        return nil
    }
    
    打赏 评论

相关推荐 更多相似问题