法I:
views.py
#encoding:utf-8
import os from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse path = '/tmp/'
def downloader(request):
filename_tmp = 'test.tmp' # test.tmp为将要被下载的文件名
filename = os.path.join(path,filename_tmp)
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' # somefilename.csv为下载后的文件名
return response
法II:
test.html
<a href="download/file/">下载</a>
urls.py
url(r'^download/file/$', 'xxx.views.download'), # xxx为项目名
xxx中的views.py
import os
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required @login_required
def download(request):
response = HttpResponse()
response['Content-Disposition'] = 'attachment;filename=downfile.txt' # downfile.txt为下载后的文件名
full_path = os.path.join('/tmp', 'filename.txt') # filename.txt为将要被下载的文件名
if os.path.exists(full_path):
response['Content-Length'] = os.path.getsize(full_path) # 可不加
content = open(full_path, 'rb').read()
response.write(content)
return response
else:
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':文件路径}),