本文代码针对的是django前后端混合项目,具体的逻辑思路也适用于前后端分离项目,需要自行修改。
django针对文件下载专门提供了StreamingHttpResponse对象用来代替HttpResponse对象,以流的形式提供下载功能。StreamingHttpResponse对象用于将文件流发送给浏览器,与HttpResponse对象非常相似,对于文件下载功能,使用StreamingHttpResponse对象更加稳定和有效。
步骤如下:
1.前端部分
前端通过a标签链接需要下载的文件,通过id来确定是哪个文件。
<div class="form-group">
<label class="col-sm-2 control-label">下载文件:</label>
<div>
<a href="{% url 'verifyForm:getDoc' verifyData.id %}"><b>{{verifyData.table_file}}</b></a>
</div>
</div>
2.后端部分
1)在views.py文件中先添加一个文件分批读取得到函数read_file()函数,该函数通过构建一个迭代器,分批处理文件,然后将这个迭代器作为结果返回。
#文件分批读取函数
def read_file(file_name,size): #file_name为文件路径,size表示分批读取文件的大小
with open(file_name,mode='rb') as fp:
while True:
c = fp.read(size)
if c:
yield c
else:
break
2)在views.py中编写文件下载函数getDoc()
from django.shortcuts import get_object_or_404
from django.http import StreamingHttpResponse
import os
#读取下载文件
def getDoc(request,id):
doc = get_object_or_404(verifyForm,id=id)
#如果模型中的文件字段有update_to的话,用注释的这两句进行拼接
# update_to,filename=str(doc.table_file).splite('/')
# filepath = '%s/media/%s'%(os.getcwd(),filename)
response = StreamingHttpResponse(read_file(filepath,512)) #调用文件分批读取函数read_file
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename = "{}"'.format(filename)
return Respnse
3)在urls.py中配置getDoc函数的路由
from django.contrib import admin
from django.urls import path,include
from . import views
app_name = 'verifyForm' #设置应用名
urlpatterns = [
#配置getDoc函数的路由
path('getDoc/<int:id>/',views.getDoc,name='getDoc'),
]