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

本文介绍了一种使用 Django 实现大文件流式下载的方法。通过定义一个文件迭代器,可以将大文件分块读取并发送给客户端,避免一次性加载整个文件到内存中。此方法适用于需要高效处理大文件下载的 Web 应用场景。

代码:

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.youkuaiyun.com/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值