对于这个问题,我有点陌生,所以我很陌生。我需要知道从哪里开始。
我正在尝试通过以下流程进行简单设置:
我知道如何在前端和python中进行处理。我的问题是,如何将文件发送到服务器(将使用GET或POST等方式提交表单),如何使它像附图所示?任何指导表示赞赏。
我的前端代码如下:
function sendfile(){
var file = document.getElementById("uploadfile").value;
$.post('localhost:22222', //this is where I am hosting the server
{SendData: file},
function(returnedArray) {
var newData = //the response from python server, in array format;
//set up different variables from the array
//update the returned_info div with the new data
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Upload your file here:
<input type="file" id="uploadfile">
<button onclick="sendfile()">Submit!</button>
</form>
<div id="returned_info">
</div>
以上代码是否正确,或者有什么我需要改进的地方?
我将如何在python服务器中正确接收请求,以便它将CSV文件转换为数组,例如this?服务器完成数据获取并从该原始数组进行计算后,如何将另一个数组发送回HTML页面以供jQuery回调使用(请参见代码)?
我正在使用this参考。
我假设您不使用jQuery,而仅使用纯JavaScript进行构建。
我使用render_template_string
而不是render_template
只是为了简化测试-您可以将所有文件放在一个文件中并运行它。
带有JavaScrip的URL /
显示表单,它使用XHR/AJAX
将文件发送到/upload
并获取结果
URL /upload
从表单获取文件并生成HTML,并将结果发送回浏览器。
import os
from flask import Flask, request, render_template, render_template_string
from werkzeug.utils import secure_filename
import pandas as pd
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '.'
@app.route('/')
def index():
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form id="my_form" method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="my_file" />
<input type="submit" id="my_button" value="Send" />
</form>
<div id="result"></div>
<script>
var my_form = document.getElementById("my_form");
var my_file = document.getElementById("my_file");
var my_button = document.getElementById("my_button");
var result = document.getElementById("result");
my_button.onclick = function(event){
var formData = new FormData(my_form);
formData.append('my_file', my_file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload', true);
xhr.addEventListener('load', function(e) {
// HTTP status message
//console.log(xhr.status);
// request.response will hold the response from the server
//console.log(xhr.response);
result.innerHTML = xhr.response;
});
xhr.send(formData);
event.preventDefault();
};
</script>
</body>
</html>''')
@app.route('/upload', methods=['POST'])
def upload():
#if request.method == 'POST': # no need if `methods=['POST']`
#if request.is_xhr(): # `is_xhr()` doesn't exist any more
# get file
#print(request.files)
temp_file = request.files.get('my_file') # `<input ... name="my_file">`
print(temp_file.filename)
# save it in
save_name = secure_filename(temp_file.filename)
full_path = os.path.join(app.config['UPLOAD_FOLDER'], save_name)
temp_file.save(full_path)
#data = pd.read_csv(full_path)
data = pd.DataFrame({
'Text': ['abc', 'def', 'ghi'],
'Number': [123, 456, 789],
})
print(data)
# convert dataFrame to HTML
table = data.to_html()
#table = data.to_html(classes="my_table", header=True)
# send generated HTML
return table
# or
# send template with embed HTML. It needs `|safe` to display HTML correctly
#return render_template_string('''DataFrame:</br>{{ table|safe }}</br>''', table=table)
if __name__ == '__main__':
app.run(debug=True)
jQuery
的EDIT:版本仅需要在<script>
中的HTML
中进行更改。
@app.route('/')
def index():
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="my_form" method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" id="my_file" name="my_file" />
<input type="submit" id="my_button" value="Send" />
</form>
<div id="result"></div>
<script>
//$("#my_form").submit(function(event){
// or
$("#my_button").click(function(event){
$.post({
url: '/upload',
data: new FormData($("#my_form")[0]),
processData: false,
contentType: false, // Using FormData, no need to process data.
}).done(function(data){
$('#result').html(data);
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
event.preventDefault();
});
// warning: when I was using `alert(event)` or `alert($("#my_form")[0]) to see values in Firefox then code doesn't work
</script>
</body>
</html>''')