无需压缩即可将文件添加到zip存档

Kim*_*Kim 4 zip go epub

在Go中,我们如何在没有压缩的情况下将文件添加到zip存档?

对于上下文,我将跟随IBM教程创建一个epub zip文件.它显示以下Python代码:

import zipfile, os

def create_archive(path='/path/to/our/epub/directory'):
    '''Create the ZIP archive.  The mimetype must be the first file in the archive 
    and it must not be compressed.'''

    epub_name = '%s.epub' % os.path.basename(path)

    # The EPUB must contain the META-INF and mimetype files at the root, so 
    # we'll create the archive in the working directory first and move it later
    os.chdir(path)    

    # Open a new zipfile for writing
    epub = zipfile.ZipFile(epub_name, 'w')

    # Add the mimetype file first and set it to be uncompressed
    epub.write(MIMETYPE, compress_type=zipfile.ZIP_STORED)

    # For the remaining paths in the EPUB, add all of their files
    # using normal ZIP compression
    for p in os.listdir('.'):
        for f in os.listdir(p):
            epub.write(os.path.join(p, f)), compress_type=zipfile.ZIP_DEFLATED)
    epub.close()
Run Code Online (Sandbox Code Playgroud)

在此示例中,不得压缩文件mimetype(仅包含内容application/epub+zip).

Go 文档确实提供了写入zip存档的一个示例,但所有文件都是压缩的.

Jam*_*dge 6

有两种方法可以将文件添加到文件中zip.Writer:Create方法和CreateHeader.虽然Create只允许您指定文件名,但该CreateHeader方法提供了更大的灵活性,包括设置压缩方法的能力.

例如:

w, err := zipwriter.CreateHeader(&zip.FileHeader{
    Name:   filename,
    Method: zip.Store,
})
Run Code Online (Sandbox Code Playgroud)

您现在可以将数据写入w与Go文档中的示例代码相同的数据,并且它将存储在zip文件中而不进行压缩.