python后端向前台返回字节流文件,浏览器访问地址自动下载文件:

from django.http.response import  StreamingHttpResponse
# 要下载的文件路径
the_file_name = "record.txt"
# 这里创建返回
response = StreamingHttpResponse(self.file_iterator(the_file_name))
# 注意格式
response['Content-Type'] = 'application/txt'
# 注意filename 这个是下载后的名字
response['Content-Disposition'] = 'attachment;filename="record.txt"'
return response

  

def file_iterator(self, file_name, chunk_size=512):
'''
# 用于形成二进制数据
:param file_name:
:param chunk_size:
:return:
'''
with open(file_name, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break

  

05-29 01:03