Django 文件下载: 使用 HttpResponse 和 FileResponse 实现数据导出
在 Django 中,可以使用 HttpResponse 和 FileResponse 等类来处理将数据以文件形式下载的请求。具体步骤如下:
- 在视图函数中获取需要下载的数据,并将其存储到一个文件中。
- 使用
HttpResponse或FileResponse类将文件发送给客户端。
下面是一个示例代码,演示如何将数据以文件形式下载:
from django.http import HttpResponse, FileResponse
import os
def download_file(request):
# 获取需要下载的数据
data = 'hello world'
# 将数据存储到一个文件中
filename = 'data.txt'
with open(filename, 'w') as f:
f.write(data)
# 构造HttpResponse或FileResponse对象
# 使用HttpResponse对象
# response = HttpResponse(open(filename, 'rb'), content_type='application/octet-stream')
# response['Content-Disposition'] = 'attachment; filename='{}''.format(filename)
# 使用FileResponse对象
response = FileResponse(open(filename, 'rb'), as_attachment=True, filename=filename)
# 删除临时文件
os.remove(filename)
return response
在上面的代码中,我们使用了 FileResponse 类来构造响应对象。FileResponse 会自动处理文件的分块传输,避免了一次性将整个文件读入内存的风险。如果不想使用 FileResponse 类,也可以使用 HttpResponse 类,但需要手动设置 Content-Disposition 头部,以告知浏览器将响应保存为附件。
原文地址: https://www.cveoy.top/t/topic/ooEP 著作权归作者所有。请勿转载和采集!