前端:
<a href="/download/">下載</a>
url.py:
urlpatterns = [
path('download/', download)
]
views.py:
from django.http import FileResponse
def download(request):
file = open('./static/download/簡歷.docx', 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
response['Content-Disposition'] = 'attachment;filename= '+'簡歷'.encode('utf-8').decode('ISO-8859-1')+'.docx'
return response
來解釋一下download函數:
1、首先是打開存放文件的目錄,‘.’表示根目錄,也就是你整個django項目的根目錄。我的“簡歷.docx”文件就放在djangoProjectName/static/download/目錄下。
2、docx使用的MIME類型是 application/vnd.openxmlformats-officedocument.wordprocessingml.document。
3、因爲文件名中有中文,如果直接在Content-Disposition中包含中文會導致文件名無法正常顯示,因此要以'簡歷'.encode('utf-8').decode('ISO-8859-1')的形式進行轉碼。
網上搜到常用的有三種方法實現文件下載,我這邊就試了這一種,其他你可以自己去搜一下然後試試。