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