压缩下载文件
views.py
from django.shortcuts import render, HttpResponse
from django.http import FileResponse
from downfile.models import Demo
import zipfile
def addzip(request):
zip_file_name = 'archive.zip' # 压缩包文件名
# 将数据库中的数据读写出来
for i in range(1, 3):
with open(f'{i}.py', 'wb')as f1:
obj = Demo.objects.get(id=i)
f1.write(obj.file_data)
# 将文件压缩到文件夹
f = zipfile.ZipFile(zip_file_name, 'a', zipfile.ZIP_DEFLATED)
f.write(f'{i}.py')
f.close()
# 将文件发送到前端下载
file = open(zip_file_name, 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = f'attachment;filename="{zip_file_name}"'
return response