gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:43:03 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com