前言
在前一周得到导师的要求,需要我配合后台人员统一完成前端+后台的编写。由于自身只搞前端,因此对后台的部分基本是不太清楚,于是乎迅速去b站进行了一波flask的学习,学习过后大概对flask就有了了解,也能够对后端的代码进行编写了
一、前端内容
1. 基本样式
采用了boostrap框架进行编写的,下图为页面渲染后的样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--viewport表示用户是否可以缩放的web页面 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>data source</title>
<link href="../static/bootstrap/css/bootstrap.css" rel="stylesheet">
<script src="../static/js/vue.global.js"></script>
<style>
/* layout.css Style */
.upload-drop-zone {
height: 200px;
border-width: 2px;
margin-bottom: 20px;
}
/* skin.css Style*/
.upload-drop-zone {
color: #ccc;
border-style: dashed;
border-color: #ccc;
line-height: 200px;
text-align: center
}
.upload-drop-zone.drop {
color: #222;
border-color: #222;
}
</style>
</head>
<body>
<div id="main">
<div class="alert alert-success" id="toggle-suc" style="display: none;">成功!很好地完成了提交。</div>
<div class="container">
<div class="panel panel-info">
<!--面板头部-->
<div class="panel-heading">
<h2 align="center">Data Source Selection</h2>
</div>
<!--面板主体-->
<div class="panel-body">
<!-- <form action="#" class="form-inline" role="form" method>-->
<div class="row">
<div class="col-md-9">
<span class="glyphicon glyphicon-plus"> </span>Load local Data
<!-- <form id="upload-form" action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" id="upload" name="upload" /> <br />
<input type="submit" value="Upload" />
</form> -->
<!--<div class="container">-->
<div class="panel panel-primary">
<div class="panel-heading" style="text-align: center;"><strong>上传文件</strong></div>
<div class="panel-body">
<!-- Standar Form -->
<h4>请选择文件</h4>
<form id="uploadForm" method="POST" enctype="multipart/form-data">
<div class="form-inline">
<div class="form-group">
<input type="file" name="files[]" id="js-upload-files"
@change="selectFile">
</div>
<button type="button" class="btn btn-sm btn-primary" id="js-upload-submit"
@click="uploadFile">上传
</button>
</div>
</form>
<!-- Drop Zone -->
<h4>或者将文件拖拽到这里</h4>
<div class="upload-drop-zone" id="drop-zone">
文件显示
</div>
</div>
</div>
<!--</div>-->
</div>
<div class="col-md-3">
<span class="glyphicon glyphicon-cloud"> </span>Server Data
<select name="selectFileList" id="selectFileList" class="form-control">
<option v-for="(item,index) in file_list" :key="item.id" :value="item.name">
{[item.name]}
</option>
</select>
<div class="col-md-1 col-md-offset-3">
<button @click="chooseFile" style="margin-top: 15px" class="btn btn-primary"
text-align="center" type="button">confirm</button>
</div>
</div>
</div>
<!-- </form>-->
</div>
</div>
</div>
<hr>
<div class="container" v-if="showOrNot">
<div class="panel panel-success">
<div class="panel-heading">
<h2 align="center">Data Exhibition</h2>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">
<h3 align="center">Inpower18480</h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr v-for="item in fileValue.length" >
<td v-for="i in fileValue[item-1]">
{[i]}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-1 col-md-offset-5">
<button class="btn btn-primary" text-align="center">confirm</button>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="../static/js/jquery-3.4.1.js"></script>
<script src="../static/bootstrap/js/bootstrap.js"></script>
<script src="../static/js/jquery.form.js"></script>
<script src="../static/js/utils.js"></script>
</html>
2. 前后端交互
三个功能:1. 点击上传按钮后需要将前端用户所选择的文件上传至对应位置;2. 右侧下拉菜单需要更新,获取对应文件夹的内容 3. 右侧点击confirm需要显示对应选择的文件
<script type="text/javascript">
window.onload = function () {
}
const { createApp } = Vue
createApp({
delimiters: ['{[', ']}'], //设置vue语法格式
data() {
return {
file_list: [],
showOrNot: false,
fileValue: []
}
},
methods: {
// 测试函数
ttt: function () {
console.log(this.fileValue)
},
// 查看点击上传文件过后的文件信息
selectFile: function () {
console.log("!!!", this.file_list)
const fileInput = document.getElementById("js-upload-files")
const file = fileInput.files[0]
console.log(file)
},
// 提交文件
uploadFile: function () {
let formData = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'post',
url: "http://127.0.0.1:5000/fileFunction/upload", //上传文件的请求路径必须是绝对路劲
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
if (data.code == 200)
commonUtil.message("提交成功", 'success');
setTimeout(function () {
window.location.reload(true);
}, 500)
},
error: function (e) {
// 这里是访问失败时被自动调用的代码
console.log(e)
commonUtil.message("提交失败", 'danger');
}
});
},
// 最后点击confirm查看文件
chooseFile: function () {
let that = this
let selectVal = $("#selectFileList").val()
console.log(selectVal)
let obj = { name: selectVal }
console.log(obj)
$.ajax({
type: "post", // 请求方式
url: "http://127.0.0.1:5000/fileFunction/getCSV", // 请求路径
data: obj,
success: function (data) { // data是形参名,代表返回的数据
if (data.code == 200)
commonUtil.message("查看成功", 'success');
// console.log("success", data);
let values = data.file_value
// 全局赋值
that.fileValue = values
that.showOrNot = true
// console.log("!", that.fileValue)
}
});
}
},
created() {
// console.log("qian", this.)
let that = this
$.ajax({
type: "post", // 请求方式
url: "http://127.0.0.1:5000/fileFunction/getFileList", // 请求路径
dataType: "json", // 预期返回一个 json 类型数据
success: function (data) { // data是形参名,代表返回的数据
console.log("success", data);
that.file_list = data
}
});
},
}).mount('#main')
</script>
二、后端内容
from flask import Blueprint, render_template, redirect, jsonify, make_response
from flask import request
import os
from werkzeug.utils import secure_filename
from utils.mongo_connection import MongoConnection
from utils.data_process import DataStorage
import pandas as pd
bp = Blueprint("datasource", __name__, url_prefix='/fileFunction')
@bp.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['files[]']
print(f)
print(request.files, 'xxxx', f)
f.save("data/" + f.filename)
# 给前端返回成功msg
data = {'message': 'Created', 'code': 200}
return make_response(jsonify(data), 200)
else:
print("get request")
return render_template('datasource.html')
"""
得到文件路径
调试成功 1-30
"""
@bp.route('/getFileList', methods=['GET', 'POST'])
def getFileList():
path = "data/"
file_list = []
file = list(os.listdir(path))
for i in range(len(file)):
temp = {'id': i, "name": file[i]}
file_list.append(temp)
return jsonify(file_list)
"""
得到csv文件前5行
调试成功 2-1
"""
@bp.route('/getCSV', methods=['GET', 'POST'])
def getCSV():
print(request)
if request.method == 'POST':
filePrefix = "data/"
filelastName = request.form['name'] # default
fileName = filePrefix + filelastName
f = pd.read_csv(fileName, nrows=5 ,encoding = 'GBK',header=None)
f = f.iloc[:, 0:10]
# 拿到前五行与前10列的二维数组
list_f = f.values.tolist()
obj = {"file_value": list_f, "code":200 , "status":"success"}
return make_response(jsonify(obj), 200)
总结
后续依然有对应的页面和后台需要进行交互,因此前端程序员可能不能只关注于自身前端的技术,也需要接触对应服务端的语言进行完善自身的知识面。