场景
在Django的View中动态生成多个文件并打包成zip进行下载。
创建临时文件
import tempfile
file_list = []
# file1
file_list.append(tempfile.TemporaryFile(mode="w+t"))
# file2
file_list.append(tempfile.TemporaryFile(mode="w+t"))
# 写入一些内容
file_list[0].write("Some text1.")
file_list[1].write("Some text2.")
向Zip写入内容
import zipfile
import io
def pack_zip():
try:
s = io.BytesIO()
zf = zipfile.ZipFile(s, "w")
for f in file_list:
# 将指针移动到文件开始处
f.seek(0)
# 读取文件内容,设定文件名写入Zip
zf.writestr("file_name.txt", f.read())
finally:
# 关闭文件流
for f in file_list:
f.close()
zf.close()
return s
在View中返回Response
import urllib.parse
from django.http.response import HttpResponse
file_data = pack_zip()
response = HttpResponse(file_data.getvalue(), content_type='application/zip')
# 文件名含有汉字时会出现乱码,需要进行处理
filename = urllib.parse.quote("下载Zip文件.zip")
response['Content-Disposition'] = f'attachment; filename={filename}; filename*=UTF-8""{filename}'
return response