【Django】Django 文件下载最佳实践

代码:

from django.http import StreamingHttpResponse

def big_file_download(request):
    # do something...

    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    the_file_name = "big_file.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)

    return response

参考资料:

http://www.jianshu.com/p/2ce715671340

http://blog.csdn.net/martin_liang/article/details/43286539

http://zhidao.baidu.com/link?url=l2plQ2oAU0A-SJzEH-OwWsLVciU91XlQwMmn3qrXhHkY9XRDFeSv09YAfQpVKZbrmKzOSFLgtA3mGmtTTjgGzJHzMI7u9WpdozQFwxq0fNW

http://www.python88.com/topic/126/

推荐:

http://www.cnblogs.com/linxiyue/p/4187484.html

http://blog.sina.com.cn/s/blog_90bc5fc60102vl7m.html

原文地址:https://www.cnblogs.com/junneyang/p/5972761.html