Django 网站文件下载:支持多种类型文件下载

本示例代码展示了使用 Django 框架实现网站文件下载功能,支持多种类型文件(PDF、PNG、DOCX 等)分别下载。

代码示例

views.py

from django.shortcuts import render
from django.http import HttpResponse, FileResponse
import os

def download(request, filename):
    file_path = os.path.join(settings.MEDIA_ROOT, filename)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/octet-stream")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    else:
        return HttpResponse('Sorry, file does not exist.')

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('download/<str:filename>/', views.download, name='download'),
]

template.html

<ul>
    <li><a href="{% url 'download' 'file1.pdf' %}">Download PDF</a></li>
    <li><a href="{% url 'download' 'file2.png' %}">Download PNG</a></li>
    <li><a href="{% url 'download' 'file3.docx' %}">Download DOCX</a></li>
</ul>

代码解释

  1. views.py: 定义了名为 download 的视图函数,该函数根据文件名使用 FileResponse 返回文件内容。
  2. urls.py: 定义了一个名为 download 的 URL 路由,用于将请求路由到 download 视图函数。
  3. template.html: 使用 URL 路由创建下载链接,将文件名作为参数传递给 download 视图函数。

总结

本示例代码演示了如何使用 Django 实现简单的文件下载功能,支持多种文件类型。您可以根据实际需求进行修改和扩展,例如添加用户权限控制、文件类型检测等功能。

Django 网站文件下载:支持多种类型文件下载

原文地址: https://www.cveoy.top/t/topic/nJxs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录