Django实现流下载

需要手动引入fileDownload.js 下载地址可前往 https://www.zhijinyu.com

1. 定义一个下载函数

    def download_excel(filename, chunk_size=512):
        with open(filename, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

2. 导入django的包 views.py

from django.http import StreamingHttpResponse
from django.utils.http import urlquote

def  test(request):
    
    # filename = " "    打开的文件路径
    response = StreamingHttpResponse(download_excel(filename=desktop_path + '\\用户角色数据统计表.xlsx'))
    response['Content-Type'] = 'application/vnd.ms-excel'  # 注意格式
    #django自带一个urlquote函数用于url编码,解决不支持中文编码问题
    response['Content-Disposition'] = 'attachment;filename=' + urlquote("用户角色数据统计表.xls") #注意filename 这个是下载后的名字
# 设置cookie让前端指定文件下载完成
    response.set_cookie('fileDownload', True, 1)
    return response

js

 $('#down-recruit').click(function () {
            var layer_index = '';
            var url = '{% url "tool:test" %}';
         $.fileDownload(url,{
            httpMethod: 'GET',
            prepareCallback:function(url){
                 layer_index = layer.load(3, {
                  shade: [0.01] //0.1透明度的白色背景
                });
            },
            successCallback:function(url){
                console.log('下载完成');
               layer.close(layer_index)
            },
            failCallback: function (html, url) {
               console.log('文件下载失败, 数据异常');
               layer.close(layer_index)
            }
         });
        })

你可能感兴趣的:(Django实现流下载)