我使用以下脚本创建ZIP文件:
import zipfile
import os
def zip_file_generator(filenames, size):
# filenames = path to the files
zip_subdir = "SubDirName"
zip_filename = "SomeName.zip"
# Open BytesIO to grab in-memory ZIP contents
s = io.BytesIO()
# 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(), content_type = "application/x-zip-compressed")
# ..and correct content-disposition
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
resp['Content-length'] = size
return resp
我从这里得到了它。
但是,由于我使用的是Python 3.x,我将s = StringIO.StringIO()
更改为s = io.BytesIO()
。
zip文件确实以正确的大小等创建,但我无法打开它。它是无效的。如果我将zip文件写入磁盘,则zip文件有效。
s
。 - PM 2Rings.getvalue()
写入二进制文件并保存到磁盘,对我来说它可以正常工作。 - PM 2Ring