zoukankan      html  css  js  c++  java
  • 文件下载(StreamingHttpResponse流式输出)

    文件下载(StreamingHttpResponse流式输出)

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

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

    参考:

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

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

    demo:下载download.txt

     

    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

  • 相关阅读:
    React 使用链表遍历组件树
    React diff 算法
    JavaScript 对象操作
    前端路由hash
    动画运动曲线
    ajax跨域问题
    js版本状态模式
    装饰者模式AOP
    swipe源码循环索引
    组合模式--超级宏命令
  • 原文地址:https://www.cnblogs.com/zealousness/p/8749227.html
Copyright © 2011-2022 走看看