前端
<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