python - Django - 创建多个文件的 Zip 并使其可下载

标签 python django file

Possible Duplicate:
Serving dynamically generated ZIP archives in Django

(如果我错过了任何可能的重复项,请随时指出我)

我看过这个片段: http://djangosnippets.org/snippets/365/

还有这个 answer:

但我想知道如何调整它们以满足我的需要:我希望压缩多个文件并通过链接下载存档(或通过 View 动态生成)。我是 Python 和 Django 的新手,所以我不知道该怎么做。

提前致谢!

最佳答案

我已在 duplicate question 上发布此消息威利链接到,但由于赏金问题不能作为重复关闭,不妨也复制到这里:

import os
import zipfile
import StringIO

from django.http import HttpResponse


def getfiles(request):
    # Files (local path) to put in the .zip
    # FIXME: Change this (get paths from DB etc)
    filenames = ["/tmp/file1.txt", "/tmp/file2.txt"]

    # Folder name in ZIP archive which contains the above files
    # E.g [thearchive.zip]/somefiles/file2.txt
    # FIXME: Set this to something better
    zip_subdir = "somefiles"
    zip_filename = "%s.zip" % zip_subdir

    # Open StringIO to grab in-memory ZIP contents
    s = StringIO.StringIO()

    # The zip compressor
    zf = zipfile.ZipFile(s, "w")

    for fpath in filenames:
        # Calculate path for file in zip
        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(zip_subdir, fname)

        # Add file, at correct path
        zf.write(fpath, zip_path)

    # Must close zip for all contents to be written
    zf.close()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
    # ..and correct content-disposition
    resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename

    return resp

关于python - Django - 创建多个文件的 Zip 并使其可下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12881294/

相关文章:

python - 使用 Mypy 与类继承的混淆 - 列表与序列

python - Django REST Framework 嵌套序列化器无效

c++ - 如何在 C++ 中进行文件检查

python - 如何在文件路径中指定当前用户变量名

java - 奇怪的路径会导致文件系统结构错误吗?

python - Pandas - Vlookup - 搜索列中的重复值

python : selecting row where y==1 and column is 0 in a matrix

python - 截断小数点后的所有数字

python - Django:如何在 post_save 信号中访问原始(未修改)实例

django - 如何应用节流只是为了在 DRF View 集中创建 Action ?