django提供文件下载,若果文件较小,解决办法是先将要传送的内容全生成在内存中,然后再一次性传入响应对象中,如下:
[Python] 纯文本查看 复制代码 def file_download(request):
# do something...
content = open("file_name", "rb").read()
return HttpResponse(content)
但是当文件内容很大时,这种方法就不行了,django文档中提到,可以向HttpResponse传递一个迭代器,流式的向客户端传递数据,如下:
[Python] 纯文本查看 复制代码 def read_file(filename, buf_size=4096):
with open(filename, "rb") as f:
while True:
content = f.read(buf_size)
if content:
yield content
else:
break
def big_file_download(request):
filename = "filename"
response = HttpResponse(read_file(filename))
return response
|