要实现文件下载功能,可以通过以下步骤在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>
这样,用户访问该链接时就会触发文件下载功能,浏览器会弹出文件下载对话框,用户可以选择保存文件或直接打开文件。