Django:实现导入功能,及下载模版

配置 setting.py ,将upload路径定义在根目录下

# 文件上传配置
UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')

 

前端

<button id="select_file" class="btn btn-primary">导入</button>
<a href="/env/file_down">下载模版</a>

js:

    $(function () {
        var file; // 定义一个全局变量,为一个文本选择器。
        file = $('<input type="file" id="upload_file"/>'); // 这样file就是jquery创建的一个文本选择器,但是因为我们并没有把它加载到页面山,所以是不可见的。
        // button的单击事件
        $('#select_file').click(function () {
            // 启动文件选择
            file.click();
        });
        // 上传文件:选择好文件后,获取选择的内容并上传到指定路径
        file.change(function (e) {
            var fileobj = file[0].files[0];
            console.log(fileobj);
            var form = new FormData();
            form.append("select_file", fileobj);
            event.target.value = null; //解决type="file" 只能上传一次的问题
            $.ajax({
                type: 'POST',
                url: '/env/upload_server_info',
                data: form,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log(data)
                    data = JSON.parse(data)
                    console.log(typeof data)
                    if (data.code == 200) {
                        toastr.success("上传成功");
                        $("#mytab").bootstrapTable('refresh');
                    }
                    else {
                        toastr.warning(data.msg);
                    }
                },
                error: function () {
                    toastr.warning("上传失败");
                }
            })
        })
    })

 

后端: 

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import xlrd
from django.http import HttpResponse, FileResponse
import os
from AutoTestSite.settings import BASE_DIR, UPLOAD_ROOT
from env.models import ServerInfo, Projects


def upload_server_info(request):
    """
    上传文件
    :param request:
    :return:
    """
    file_obj = request.FILES.get('select_file')
    # 创建upload文件夹
    if not os.path.exists(UPLOAD_ROOT):
        os.makedirs(UPLOAD_ROOT)
    try:
        if file_obj is None:
            return HttpResponse('请选择要上传的文件')
        # 循环二进制写入
        f = open(os.path.join(BASE_DIR, UPLOAD_ROOT, file_obj.name), 'wb')
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()
    except Exception as e:
        return HttpResponse(json.dumps({"code": 300, "msg": "上传文件失败"}))
    # 写入数据库
    return parse_xls(file_obj.name)


def parse_xls(filename):
    # print(UPLOAD_ROOT + "\\" + filename)
    file_path = UPLOAD_ROOT + "\\" + filename
    # print(file_path)
    try:
        # 打开上传 excel 表格
        readboot = xlrd.open_workbook(r"%s" % file_path)
    except FileNotFoundError:
        print('没有找到文件')
    sheet = readboot.sheet_by_index(0)
    # 获取excel的行和列
    nrows = sheet.nrows
    ncols = sheet.ncols
    # print(ncols, nrows)
    from common import encrypt
    # 循环插入每行数据
    for i in range(1, nrows):
        row = sheet.row_values(i)
        project_name = row[0]
        server_ip = row[2]
        app_port = int(row[3])
        app = row[4]
        cpu = int(row[5])
        memory = int(row[6])
        disk = int(row[7])
        login_name = row[8]
        login_pwd = encrypt.des_encrypt(str(row[9]))
        status = int(row[10])
        print(row)
        print(str(server_ip))
        from common import validate
        if not validate.check_ip(str(server_ip)):
            print("ip格式不正确")
            return HttpResponse(json.dumps({"code": 400, "msg": "{},ip格式不正确".format(server_ip)}))

        try:
            # 检查是否存非法的项目名
            project_instance = Projects.objects.get(project_name=project_name)
        except Exception as e:
            return HttpResponse(json.dumps({"code": 300, "msg": "项目名称[{}]不存在".format(project_name)}))
        # 判断库中是否存在该ip
        if ServerInfo.objects.filter(server_ip=server_ip).count() != 0:
            return HttpResponse(json.dumps({"code": 400, "msg": "{},已存在".format(server_ip)}))
        try:
            # 写入数据库
            ServerInfo.objects.create(project_name=project_instance, server_ip=server_ip, app_port=app_port, app=app,
                                      cpu=cpu,
                                      memory=memory, disk=disk, login_name=login_name,
                                      login_pwd=login_pwd, status=status)
        except Exception as e:
            return HttpResponse(json.dumps({"code": 400, "msg": "导入失败,请检查导入数据"}))

    return HttpResponse(json.dumps({"code": 200, "msg": "导入成功"}))


def file_down(request):
    """
    下载导入服务器模版
    :param request:
    :return:
    """
    file = open(os.path.join(BASE_DIR, UPLOAD_ROOT, "template.xlsx"), 'rb')
    print(os.path.join(BASE_DIR, UPLOAD_ROOT, "template.xlsx"))
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="template.xlsx"'
    return response

 

posted @ 2020-11-26 21:14  秋寻草  阅读(442)  评论(0编辑  收藏  举报