Django File Download Tutorial
To achieve the function of downloading files, you can implement the following steps in Django.
- Create a view function in the views.py file to handle file download requests.
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)
- Configure the URL routing for this view function in the urls.py file.
from django.urls import path
from . import views
urlpatterns = [
path('download/<str:file_path>/', views.download_file, name='download_file'),
]
- Add a download link in the template file and call the corresponding view function.
<a href="{% url 'download_file' file_path %}">Download File</a>
In this way, when users access the link, it will trigger the file download function, and the browser will prompt a file download dialog where users can choose to save the file or open it directly.