Django的Httpresponse对象允许将迭代器作为传入参数。StreamingHttpResponse对象取代HttpRseponse对象,更适合与文件下载。服务器上的文件已经通过文件流传输到浏览器上,单文件流会一乱码的方式显示在浏览器中,而不是下载在硬盘中,可以给StreamHttpResponse对象的Content_type 和 Content_Disposition字段赋值 Content_type :http://tool.oschina.net/commons(指明文件的格式)
当文件为多个文件是自动生成zip格式的压缩包
from django.http import StreamingHttpResponse
def big_file_download(request):
def file_iterator(file_name, chunk_size=512):
with open('static/app/app.apk') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
the_file_name = "big_file.apk"
response = StreamingHttpResponse(file_iterator(the_file_name))
response['Content-Type'] = 'application/application/vnd.android.package-archive'
response['Content-Disposition'] = 'attachment;filename=" {0}"'.format(the_file_name)
return response