django 如何将zip文件返回给前端下载
您可以使用HttpResponse来返回zip文件,设置Content-Type为application/zip,Content-Disposition为attachment,filename为您想要的文件名。以下是示例代码:
import zipfile
from django.http import HttpResponse
def download_zip(request):
# 创建一个zip文件
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, 'w') as zip_file:
# 将文件添加到zip文件中
file_path = 'path/to/your/file'
zip_file.write(file_path)
# 返回HttpResponse对象,Content-Type设置为application/zip,Content-Disposition设置为attachment
# filename设置为您想要的文件名
response = HttpResponse(buffer.getvalue(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="your_file_name.zip"'
return response
``
原文地址: https://www.cveoy.top/t/topic/fJU8 著作权归作者所有。请勿转载和采集!