python后端向前台返回字节流文件


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

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM