如何使用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.

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.

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
}