StreamingHttpResponse是 HttpResponse下的子类,操作等方便.这个也是导包最少的方法了吧
# 下载模板
# StreamingHttpResponse可以以流的方式进行下载
def download(request):
def file_itertor(file_name,chunk_size=512):
with open(file_name,'rb') as f:
while True:
c=f.read(chunk_size)
if c:
yield c
else:
break
file_name=r'E:\pro\export\text2 .csv'
global download_file
download_file='text2.csv'
response=StreamingHttpResponse(file_itertor(file_name))
# 设置头信息,告诉浏览器这是个文件
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(download_file)
return response