Django 如何将 Zip 文件返回给前端下载
可以使用 HttpResponse 对象将 Zip 文件返回给前端下载。具体步骤如下:
-
在视图函数中,定义一个
HttpResponse对象,将 Zip 文件的二进制数据作为参数传递给HttpResponse对象的content属性。 -
设置
HttpResponse对象的content_type属性为'application/zip',表示返回的是 Zip 文件。 -
设置
HttpResponse对象的Content-Disposition头信息,用于指定浏览器打开下载框,而不是直接打开文件。可以设置为'attachment; filename=filename.zip',其中 filename 是下载文件的名称。 -
返回
HttpResponse对象。
示例代码:
import os
from django.http import HttpResponse
def download_zip(request):
# 获取 Zip 文件的路径
zip_file_path = '/path/to/zip/file.zip'
# 读取 Zip 文件的二进制数据
with open(zip_file_path, 'rb') as f:
zip_data = f.read()
# 创建 HttpResponse 对象,并设置 content、content_type、Content-Disposition 属性
response = HttpResponse(zip_data, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response
在模板中,可以使用超链接或表单提交等方式触发该视图函数,从而下载 Zip 文件。例如:
<a href="{% url 'download_zip' %}">下载 Zip 文件</a>
原文地址: https://www.cveoy.top/t/topic/opuv 著作权归作者所有。请勿转载和采集!