一、使用HttpResponse返迴文件
在Django中,我們可以使用HttpResponse對象返回一個文件給用戶下載。
from django.http import HttpResponse, FileResponse import os def download_file(request): file_path = os.path.join('/path/to/your/file/', 'your_file_name') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404
上述代碼首先判斷文件是否存在,如果存在則打開文件,將文件內容讀取到HttpResponse對象中並設置Content-Disposition為inline。這樣就能夠在網頁中直接瀏覽文件內容,或在瀏覽器中自動下載文件。
二、使用FileResponse返迴文件
在Django2.x中,我們也可以使用FileResponse對象返回一個文件給用戶下載。
from django.http import HttpResponse, FileResponse import os def download_file(request): file_path = os.path.join('/path/to/your/file/', 'your_file_name') if os.path.exists(file_path): response = FileResponse(open(file_path, 'rb')) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(your_file_name) return response raise Http404
上述代碼中,我們首先判斷文件是否存在,如果存在則使用FileResponse打開文件,並設置Content-Type為application/octet-stream,Content-Disposition為attachment,這樣瀏覽器就會提示用戶下載文件。
三、使用django-sendfile返迴文件
Django-sendfile是一個第三方庫,可以通過它實現快速而安全地提供文件下載功能。
首先安裝django-sendfile:
pip install django-sendfile
然後在項目的settings.py文件中配置:
INSTALLED_APPS = [ # ... 'django_sendfile', # ... ]
最後,可以使用django-sendfile來提供文件下載功能:
from django_sendfile import sendfile import os def download_file(request): file_path = os.path.join('/path/to/your/file/', 'your_file_name') if os.path.exists(file_path): return sendfile(request, file_path, attachment=True) raise Http404
上述代碼中,我們首先判斷文件是否存在,如果存在則使用sendfile方法返迴文件,通過傳遞attachment=True參數來設置Content-Disposition為attachment,這樣瀏覽器就會提示用戶下載文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154618.html