文件下载(StreamingHttpResponse流式输出)

时间:2023-03-09 19:42:12
文件下载(StreamingHttpResponse流式输出)

文件下载(StreamingHttpResponse流式输出)

HttpResponse会直接使用迭代器对象,将迭代器对象的内容存储成字符串,然后返回给客户端,同时释放内存。可以当文件变大看出这是一个非常耗费时间和内存的过程。

而StreamingHttpResponse是将文件内容进行流式传输,数据量大可以用这个方法。

参考:

http://blog.****.net/gezi_/article/details/78176943?locationNum=10&fps=1

https://yq.aliyun.com/articles/44963

demo:下载download.txt

文件下载(StreamingHttpResponse流式输出)

from django.shortcuts import render
from django.http import StreamingHttpResponse
from django_demo.settings import BASE_DIR

# Create your views here.
def download(request):
    def filetostream(filename,streamlength=512):
        file=open(filename,'rb')
        while True:
            stream=file.read(streamlength)
            if stream:
                yield stream
            else:
                break
 print(BASE_DIR)
    response = StreamingHttpResponse(filetostream(BASE_DIR+'/file_download_demo/download.txt'))
    # response=StreamingHttpResponse(filetostream('download.txt')) # 无法直接读取当前文件夹下文件,必须用settings.py中的BASE_DIR确定绝对路径,为什么?
 response['Content-Type'] = 'application/octet-stream'
 response['Content-Disposition'] = 'attachment;filename="download.txt"'
 return response