码迷,mamicode.com
首页 > 其他好文 > 详细

Django 之 下载文件

时间:2015-09-08 19:47:18      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

法I:

views.py

 1 #encoding:utf-8
 2 import os
 3 
 4 from django.core.servers.basehttp import FileWrapper
 5 from django.http import HttpResponse
 6 
 7 path = /tmp/
 8 def downloader(request):
 9     filename_tmp = test.tmp   # test.tmp为将要被下载的文件名
10     filename = os.path.join(path,filename_tmp)
11     wrapper = FileWrapper(file(filename))
12     response = HttpResponse(wrapper, content_type=text/plain)
13     response[Content-Length] = os.path.getsize(filename)
14     response[Content-Disposition] = attachment; filename="somefilename.csv"    # somefilename.csv为下载后的文件名
15     return response

 

法II:

test.html

<a href="download/file/">下载</a>

 urls.py

1 url(r^download/file/$, xxx.views.download),    # xxx为项目名

xxx中的views.py

 1 import os
 2 from django.http import HttpResponse
 3 from django.contrib.auth.decorators import login_required
 4 
 5 @login_required
 6 def download(request):
 7     response = HttpResponse()
 8     response[Content-Disposition] = attachment;filename=downfile.txt    # downfile.txt为下载后的文件名
 9     full_path = os.path.join(/tmp, filename.txt)    # filename.txt为将要被下载的文件名
10     if os.path.exists(full_path):
11         response[Content-Length] = os.path.getsize(full_path)    #  可不加
12         content = open(full_path, rb).read()
13         response.write(content)
14         return response
15     else:
16         return HttpResponse(u文件未找到)

 

法III:

test.html

<a href="download/downfile.txt">下载</a>

urls.py

 1 url(r^download/(?P.*)$, django.views.static.serve,{document_root:文件路径}), 

 

Django 之 下载文件

标签:

原文地址:http://www.cnblogs.com/liuq/p/4792557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!