简单的django 框架下的下载文件功能的开发

 
  
  1. #view.py
  2. #使用zip的形式,将某个文件夹下的所有文件进行下载
  3. def download_conf_zipfile(request): 
  4.   import tempfile, zipfile 
  5.   from django.http import HttpResponse 
  6.   from django.core.servers.basehttp import FileWrapper 
  7.  
  8.   temp = tempfile.TemporaryFile() 
  9.   archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) 
  10.   src = "your src path" 
  11.   files = os.listdir(src) 
  12.  
  13.   for filename in files: 
  14.     archive.write(src+'/'+filename, filename) 
  15.   archive.close() 
  16.   wrapper = FileWrapper(temp) 
  17.   response = HttpResponse(wrapper, content_type='application/zip'
  18.   response['Content-Disposition'] = 'p_w_upload; filename=test.zip' 
  19.   response['Content-Length'] = temp.tell() 
  20.   temp.seek(0
  21.   return response 
  22.                    

在url.py中添加路径

 
  
  1. #url.py
  2. url(r'^download$','views.download_conf_zipfile',name='views.download_conf_zipfile'

在页面中添加href链接:


 
  
  1. <a href="${ url('config.views.download_conf_zipfile')}" class="Button round" target="_blank"><span title = "DownLoad">Down Lo 
  2. d</sapn></a> 

出现的问题:

在页面展示层需要加 target="_blank"字段,表示在新的页面打开超链接

否则,点击页面跳转到空白页,并不进行文件下载

使用target="_blank"的情况介绍

http://www.webjx.com/html-xhtml/webxhtml-22555.html

由于需求简单,并没有对大文件进行考虑,具体可以看

http://hi.baidu.com/acmtiger/blog/item/e4e5b1874f529bb10df4d2b4.html