简单的django 框架下的下载文件功能的开发
- #view.py
- #使用zip的形式,将某个文件夹下的所有文件进行下载
- def download_conf_zipfile(request):
- import tempfile, zipfile
- from django.http import HttpResponse
- from django.core.servers.basehttp import FileWrapper
- temp = tempfile.TemporaryFile()
- archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
- src = "your src path"
- files = os.listdir(src)
- for filename in files:
- archive.write(src+'/'+filename, filename)
- archive.close()
- wrapper = FileWrapper(temp)
- response = HttpResponse(wrapper, content_type='application/zip')
- response['Content-Disposition'] = 'p_w_upload; filename=test.zip'
- response['Content-Length'] = temp.tell()
- temp.seek(0)
- return response
在url.py中添加路径
- #url.py
- url(r'^download$','views.download_conf_zipfile',name='views.download_conf_zipfile')
在页面中添加href链接:
- <a href="${ url('config.views.download_conf_zipfile')}" class="Button round" target="_blank"><span title = "DownLoad">Down Lo
- 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
转载于:https://blog.51cto.com/pupulllll/851468