【转】Django下载大文件和压缩zip文件

01.import os, tempfile, zipfile  
02.from django.http import HttpResponse  
03.from django.core.servers.basehttp import FileWrapper  
04. 
05. 
06.def send_file(request):  
07.    """                                                                          
08.    Send a file through Django without loading the whole file into               
09.    memory at once. The FileWrapper will turn the file object into an            
10.    iterator for chunks of 8KB.                                                  
11.    """ 
12.    filename = __file__ # Select your file here.                                  
13.    wrapper = FileWrapper(file(filename))  
14.    response = HttpResponse(wrapper, content_type='text/plain')  
15.    response['Content-Length'] = os.path.getsize(filename)  
16.    return response  
17. 
18. 
19.def send_zipfile(request):  
20.    """                                                                          
21.    Create a ZIP file on disk and transmit it in chunks of 8KB,                  
22.    without loading the whole file into memory. A similar approach can           
23.    be used for large dynamic PDF files.                                         
24.    """ 
25.    temp = tempfile.TemporaryFile()  
26.    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)  
27.    for index in range(10):  
28.        filename = __file__ # Select your files here.                             
29.        archive.write(filename, 'file%d.txt' % index)  
30.    archive.close()  
31.    wrapper = FileWrapper(temp)  
32.    response = HttpResponse(wrapper, content_type='application/zip')  
33.    response['Content-Disposition'] = 'attachment; filename=test.zip' 
34.    response['Content-Length'] = temp.tell()  
35.    temp.seek(0)  
36.    return response

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhangzhenhu/archive/2011/01/27/6165917.aspx

转载于:https://www.cnblogs.com/xuq22/archive/2011/07/02/3769379.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值