【发布时间】:2018-10-29 21:34:46
【问题描述】:
有相关的问题here 和here 但它们并没有解决我的问题。
假设我有一个像这样的文件testdata.csv:
A,B
1,3
2,4
并且我希望用户允许上传文件,然后——为了简单起见——在同一页面上显示其内容,而不影响该页面上的任何其他元素。所以我想要的结果是这样的:
我该怎么做?我发现了几种使用form 加载文件并将其(修改后的)内容发送回(例如下载)的方法,但我很难找到一种解决方案来将JSON 响应传回修改页面(这里:添加表格)。
这是我的全部代码:
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
# Initialize the Flask application
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_table', methods=["POST", "GET"])
def get_table():
# how to catch the file here and send its content back?
# file = ????
# print(file)
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]])
# if I use a form, I can use
# file = request.files['myfile']
# however, how do I then send the JSON response?
if __name__ == '__main__':
app.run(debug=True)
还有我的index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-center text-muted">Some great stuff</h3>
</div>
<hr class="mb-4">
<div class="custom-file">
<input id="myfile" name="myfile" type="file" class="custom-file-input">
<label for="myfile" class="custom-file-label">
Choose file...
</label>
</div><br><br>
<button class="btn btn-primary" type="button" id="upload_document">Upload and process!</button>
<hr class="mb-4">
<table id="pretty_table" class="table table-striped"></table>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('#upload_document').bind('click', function() {
$.getJSON('/_get_table', {
// what to pass here?
}, function(data) {
if (table !== null) {
table.destroy();
table = null;
$("#pretty_table").empty();
}
table = $("#pretty_table").DataTable({
data: data.my_table,
columns: data.columns
});
});
return false;
});
$('.custom-file-input').on('change', function() {
let fileName = $(this).val().split('\\').pop();
$(this).next('.custom-file-label').addClass("selected").html(fileName);
});
});
</script>
</body>
</html>
【问题讨论】:
-
搜索如何使用ajax上传文件(不难找到很多结果)。需要使用 FormData API 和 $.ajax 而不是简单的
getJSON -
@charlietfl:好的,感谢您的评论。你的意思是,像this 这样的东西?以前从未使用过这个;让我们看看我是否让它工作......如果它对你来说不是太多的工作,我将非常感谢一个答案(html / jquery部分就足够了),谢谢!
-
是的...这是该链接中的基础知识
-
@charlietfl: 好的,这些东西总是让我头疼,但我会尝试... :)
-
已经写在那个链接里了。只需将选择器与表单匹配即可