文件下载功能django+js

转:https://www.cnblogs.com/supery007/p/9360188.html

1. 功能叙述

前端web页面通过访问url+id的形式访问url
lottery/draw/(?P<pk>(d+))/download/
后端代码通过orm查询pk相关数据
过滤出自己想要的字段

2. 前端页面

<a onclick="downloadFilebyAjax(this,'{{ period.id }}')" href="javascript:;" title="下载">
         <i class="layui-icon">&#xe601;</i>#下载图标
</a>
复制代码
    /*下载统计*/
    function downloadFilebyAjax(obj, id) {
        layer.confirm('确认要下载吗?', function (index) {
            $.ajaxSetup({
                data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
            });
            $.ajax({
                type: "post",
                url: id + '/download/',
                dataType: "json",
                success: function (data) {
                    if (data.status) {
                        console.log(data.filePath, "文件下载中... ...");
                        window.location.href = data.filePath;
                        layer.msg(data.msg, {icon: 6, time: 1000});
                    } else {
                        layer.msg(data.msg, {icon: 5, time: 1000});
                    }
                },
                error: function (data) {
                    console.log("对不起,网络错误,请稍后重试或联系管理员");
                }
            });
        });
    }
复制代码

3. 后端功能

复制代码
def download_draw(request,pk):
    if request.method =="POST":
        data = {'status':True,'msg': '下载成功','filePath':''}
        searia_list= huodong_models.SearialNum.objects.filter(period_id=pk)
        xls_name = searia_list[0].period.title+'.xls'
        xls_path =os.path.join(settings.BASE_DIR, 'static','download',xls_name)
        if os.path.exists(xls_path):
            os.remove(xls_path)
        book = xlwt.Workbook(encoding='utf-8')
        sheet = book.add_sheet(searia_list[0].period.title, cell_overwrite_ok=True)
        # 第0行写入标题
        sheet.write(0,0,'期号')
        sheet.write(0,1,'抽奖码')
        sheet.write(0,2,'会员账号')
        sheet.write(0,3,'获得奖品')
        sheet.write(0,4,'使用状态')
        # 初始行,写入数据从第一行开始写入
        line = 1
        manipulation(searia_list,line,sheet)
        book.save(xls_path)
        if os.path.exists(xls_path):
            filePath = '/static/download/%s' % xls_name
            data['filePath']=filePath
        else:
            data['status']=False
            data['msg']='下载失败'
        return JsonResponse(data)
    return HttpResponse('无效请求')
复制代码
复制代码
def manipulation(searia_list,line,sheet):
    for searia in searia_list:
        vip_acount = ''
        prize = ''
        style = 0
        if searia.status == 1:
            vip_acount = searia.userinfo.vip_acount
            prize = searia.userinfo.prize
            style = 2
        sheet.write(line, 0, searia.period.period)
        sheet.write(line, 1, searia.searial)
        sheet.write(line, 2, vip_acount)
        sheet.write(line, 3, prize)
        sheet.write(line, 4, searia.get_status_display())
        line += 1
复制代码

4. 说明代码思路

复制代码
先初始化execl文件第0行标题名称
之后通过数据库取出的数据生成一个数据列表
初试行位第一行一次循环写入每条字段过滤的数据
初试行数以此累加
最后保存execl文件
然后将服务器的保存的地址返回给前端
通过window.location.href来进行访问实现下载
复制代码
原文地址:https://www.cnblogs.com/baili-luoyun/p/11557555.html