views.py视图函数

下载文件使用FileResponse,添加返回头部参数Content-Type和Content-Disposition

from MyDjango.settings import BASE_DIR
from django.views import View
from django.http import FileResponse, HttpResponse
import os
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class DownPage(View):
    def get(self, request):
        """访问web页面"""
        return render(request, 'downfile.html')
class DownPDF(View):
    def get(self, request):
        """下载pdf接口"""
        # 文件路径
        file_path = os.path.join(BASE_DIR, 'static', "python1.pdf")
        print("11111111111111111111111")
        print(file_path)
        file = open(file_path, 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="python1.pdf"'
        return response

urls.py设置网页访问地址和文件下载地址

urlpatterns = [
    url('^down$', views.DownPage.as_view()),
    url('^downpdf$', views.DownPDF.as_view())

web页面访问

点击下载效果

在浏览器直接访问下载地址http://localhost:8000/downpdf 也可以下载

文件名称带中文

下载的文件名称带中文的时候,需要转码,转成ISO-8859-1编码

response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        att = 'attachment; filename=python悠悠1.pdf.exe'
        response['Content-Disposition'] = att.encode('utf-8', 'ISO-8859-1')
        return response