Django 之 下载文件
法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':文件路径}),