[英]send post data from javascript to python server
我正在尝试使用 JavaScript 录制音频并将其发送到 Python 服务器。 至于现在,我已经运行了它并且记录工作正常。 使用 AJAX 发布和获取数据,我试图传递它,但它无法发送到 Python。
这是我的代码:
JavaScript:
function submit(blob) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var fd = new FormData();
base64data = reader.result;
console.log(base64data);
fd.append('file', base64data, 'audio.ogg');
$.ajax({
type: 'POST',
url: '/',
data: fd,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data'
}).done(function(data) {
console.log(data);
});
}
蟒蛇服务器:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html")
@app.route('/', methods=['POST', 'GET'])
def get_data():
with open('./audio.ogg', 'wb') as f:
f.write(request.data)
f.close()
print("FILE CLOSED")
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
在您的 JavaScript 中,您尝试将字符串作为文件发送,您应该发送文件/blob。
见下文
function submit(blob) {
var fd = new FormData();
fd.append('file', blob, 'audio.ogg');
$.ajax({
type: 'POST',
url: '/',
data: fd,
cache: false,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
}
在您的服务器端代码中,您应该使用request.files
来访问上传的文件。
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html")
@app.route('/', methods=['POST', 'GET'])
def get_data():
request.files["file"].save('./audio.ogg')
print("FILE CLOSED")
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.