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