1:使用HttpResponse
from django.shortcuts import HttpResponse
def file_download(request):
file=open('/home/dianwei/new_project/media/down_load.tar.gz','rb') # 可以改变读的方式
response =HttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="down_load.tar.gz"'
return response
2:使用StreamingHttpResponse
from django.http import StreamingHttpResponse
def file_download(request):
file=open('/home/dianwei/new_project/media/down_load.tar.gz','rb')
response =StreamingHttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="down_load.tar.gz"'
return response
3:使用FileResponse
from django.http import FileResponse
def file_download(request):
file=open('/home/dianwei/new_project/media/down_load.tar.gz','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="down_load.tar.gz"'
return response

本文介绍了如何使用Django实现文件下载功能,通过HttpResponse、StreamingHttpResponse和FileResponse三种方式,每种方式都展示了具体的代码实现过程。
1886

被折叠的 条评论
为什么被折叠?



