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

前端

<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


def upload_server_info(request):

    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()

        # 写入数据库
        print("准备写入")
        parse_xls(file_obj.name)
    except Exception as e:
        return HttpResponse(json.dumps({"code": 300, "msg": "FAIL"}))

    return HttpResponse(json.dumps({"code": 200, "msg": "OK"}))


from env.models import ServerInfo, Projects


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:
        print('没有找到文件')
    sheet = readboot.sheet_by_index(0)
    # 获取excel的行和列
    nrows = sheet.nrows
    ncols = sheet.ncols
    print(ncols, nrows)
    from common import encrypt
    # orm插入数据
    for i in range(1, nrows):
        row = sheet.row_values(i)
        project_name = row[0]
        server_ip = row[2]
        app_port = row[3]
        app = row[4]
        cpu = row[5]
        memory = row[6]
        disk = row[7]
        login_name = row[8]

        login_pwd = encrypt.des_encrypt(str(row[9]))
        status = int(row[10])
        print(row)
        print(project_name)
        project_instance = Projects.objects.get(project_name=project_name)
        print(123, project_instance)
        # if project_instance:
        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)
        # else:
        # return HttpResponse(json.dumps({"code": 400, "msg": "项目名不正确"}))


def file_down(request):
    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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章