要實現文件下載功能,可以通過以下步驟在Django中實現:
from django.http import FileResponse
import os
def download_file(request, file_path):
file_path = os.path.join(settings.MEDIA_ROOT, file_path)
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
response = FileResponse(f)
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(file_path)
return response
else:
# 文件不存在的處理邏輯
return HttpResponse("File not found", status=404)
from django.urls import path
from . import views
urlpatterns = [
path('download/<str:file_path>/', views.download_file, name='download_file'),
]
<a href="{% url 'download_file' file_path %}">Download File</a>
這樣,用戶訪問該鏈接時就會觸發文件下載功能,瀏覽器會彈出文件下載對話框,用戶可以選擇保存文件或直接打開文件。