有三种下载方式,点击即可进行下载。
下载的图片:
项目为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实现文件下载。



