我正在尝试从页面上传一个csv文件并将其发送到由python和flask组成的后端,所有这些工作正常,因为知道因为后端返回:
127.0.0.1 - - [15 / Apr / 2018 15:37:07]“GET / medal HTTP / 1.1”200
但POST上没有任何内容。几乎尝试了一切,但没有连接或消息。
BACKEND POST:
import pandas
from calest import calest_app, client
from flask import request, jsonify
from..models.Medals import Medal
db = client.estadisticas
collection = db.medallas
@calest_app.route('/result', methods = ["POST"])
def post_discipline():
csv_received = request.files['file']
csv_file = pandas.read_csv(csv_received)
discipline_result = Medal(csv_file).get_medals_discipline()
gender_result = Medal(csv_file).get_medals_gender()
city_result = Medal(csv_file).get_medals_city()
country_result = Medal(csv_file).get_medals_country()
medals_result = Medal(csv_file).get_medals_by_medals()
sport_result = Medal(csv_file).get_medals_by_sport()
cursor = collection.insert({
"discipline": discipline_result,
"gender": gender_result,
"city": city_result,
"country": country_result,
"medal": medals_result,
"sport": sport_result
})
return jsonify("Added"), 201
FRONTEND AJAX:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </script>
< script >
$("#form").on("submit", function (e) {
var fileSelect = $("#csvFile");
var files = fileSelect[0].files;
// Create a new FormData object.
var formData = new FormData();
debugger;
formData.append("#csvFile", files[0].name, files[0], files[0].name);
<!--csv_received = request.-- >
$.ajax({
url: "http://localhost:5000/result",
method: "POST",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
debugger;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
})
});
</script>
答案 0 :(得分:0)
formData.append
最多需要3个参数,你通过了4个
第一个参数是字段名称(不是你拥有的id选择器)
第二个是File / Blob / string数据(放置文件名的位置)。
第三个字段是文件名,实际上只有在传递Blob时才需要
由于您在服务器代码中使用file
作为字段名称,因此将其用作第一个参数
formData.append("file", files[0]);