栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

Django文件下载

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django文件下载

效果


有三种下载方式,点击即可进行下载。
下载的图片:

代码:

项目为MyDjango,用到了一个项目应用index。
MyDjango的urls.py

from django.urls import path, include
urlpatterns = [
    # 指向index的路由文件urls.py
    path('', include(('index.urls', 'index'), namespace='index')),
]

index的urls.py

from django.urls import path
from . import views

urlpatterns = [
    # 定义首页的路由
    path('', views.index, name='index'),
    path('download/file1', views.download1, name='download1'),
    path('download/file2', views.download2, name='download2'),
    path('download/file3', views.download3, name='download3'),
]

index的views.py

from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.http import StreamingHttpResponse
from django.http import FileResponse

def index(request):
    return render(request, 'index.html')

def download1(request):
    file_path = 'abc.jpeg'
    try:
        r = HttpResponse(open(file_path, 'rb'))
        r['content_type'] = 'application/octet-stream'
        r['Content-Disposition'] = 'attachment; filename=dow1.jpg'
        return r
    except Exception:
        raise Http404('Download error')

def download2(request):
    file_path = 'abc.jpeg'
    try:
        r = StreamingHttpResponse(open(file_path, 'rb'))
        r['content_type'] = 'application/octet-stream'
        r['Content-Disposition'] = 'attachment; filename=dow2.jpg'
        return r
    except Exception:
        raise Http404('Download error')

def download3(request):
    file_path = 'abc.jpeg'
    try:
        f = open(file_path, 'rb')
        r = FileResponse(f, as_attachment=True, filename='dow3.jpg')
        return r
    except Exception:
        raise Http404('Download error')

templates的index.html




HttpResponse-下载

StreamingHttpResponse-下载
FileResponse-下载
说明
  • 视图函数download1使用HttpResponse实现文件下载。
  • 视图函数download2使用StreamingHttpResponse实现文件下载。
  • 视图函数download3使用FileResponse实现文件下载。
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1037641.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号