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

  • 相关阅读:
    洛谷 P3391文艺平衡树 【fhq_treap】
    食物链(转自yekehe2002大神)
    TX
    黑匣子——KEY
    Splay初学习
    BZOJ2330_糖果_KEY
    BZOJ3224_普通平衡树_KEY
    BZOJ2730_矿场搭建_KEY
    BZOJ1452_Count_KEY
    初识主席树_Prefix XOR
  • 原文地址:https://www.cnblogs.com/zealousness/p/8749227.html
Copyright © 2011-2022 走看看