1、使用HttpResponse
路由url:
url(r'^download/',views.download,name="download"),
views.py:
from django.shortcuts import HttpResponse
def download(request):
file = open('crm/models.py', 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
response['Content-Disposition'] = 'attachment;filename="models.py"'
return response
2、使用StreamingHttpResponse
from django.http import StreamingHttpResponse
def download(request):
file=open('crm/models.py','rb')
response =StreamingHttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
3、使用FileResponse
from django.http import FileResponse
def download(request):
file=open('crm/models.py','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
推荐使用FileResponse,FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。