【问题标题】:Add file to zip archive without compression将文件添加到 zip 存档而不压缩
【发布时间】:2014-05-17 23:26:39
【问题描述】:

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

对于上下文,我将跟随 IBM tutorial 创建一个 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()

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

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

【问题讨论】:

    标签: go zip epub


    【解决方案1】:

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

    例如:

    w, err := zipwriter.CreateHeader(&zip.FileHeader{
        Name:   filename,
        Method: zip.Store,
    })
    

    您现在可以将数据写入w,就像在 Go 文档中的示例代码中一样,它将存储在未压缩的 zip 文件中。

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      相关资源
      最近更新 更多