django 中实现文件下载的3种方式
方法一:使用HttpResponse
from django.shortcuts import HttpResponse
def file_down(request):
file=open('/home/amarsoft/download/example.tar.gz','rb')
response =HttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="example.tar.gz"'
return response
方法二:使用StreamingHttpResponse
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from django.http import StreamingHttpResponse
def file_down(request):
file=open('/home/amarsoft/download/example.tar.gz','rb')
response =StreamingHttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="example.tar.gz"'
return response
方法三:使用FileResponse
from django.http import FileResponse
def file_down(request):
file=open('/home/amarsoft/download/example.tar.gz','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="example.tar.gz"'
return response