我有一个网页,可以使用webcamjs从网络摄像头捕获图像。我在后端有一个烧瓶服务器,它应该接受图像和另一个表单数据。我无法使用XMLHttpRequest将图像发送到Flask服务器。
signup.html
<form method="POST" enctype="multipart/form-data" id="myForm">
<table>
<tr>
<td>Name/EmailId</td>
<td>: <input type="text" name="userID"></td>
</tr>
<tr>
<td><input type="button" value="Upload" onclick="upload()"></td>
</tr>
</table>
</form>
<div id="my_camera"></div>
<input type="button" onclick="snap()" value="Snap">
<div id="results"></div>
的JavaScript
function ShowCam() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
}
window.onload= ShowCam;
function snap() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="image" src="'+data_uri+'"/>';
} );
}
function upload() {
console.log("Uploading...")
var image = document.getElementById('image').src;
var form = document.getElementById('myForm');
var formData = new FormData(form);
formData.append("file", image);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/signup");
xmlhttp.send(formData);
console.log(formData.get('file'));
console.log(formData.get('userID'));
}
正如您在上面的javascript代码中看到的那样,我有console.log用于&#39; file&#39;和&#39; userID&#39;。这在chrome dev-tools中正确显示,但数据不会转到烧瓶服务器。我没有收到任何错误消息。
的Python
@app.route('/signup', methods=['GET','POST'])
def signup():
if request.method == 'POST':
return jsonify(request.form['userID'], request.form['file'])
return render_template('signup.html')
我尝试过简单地返回那些没有工作的return jsonify(request.form['userID'])
。
PYTHON DEBUG
127.0.0.1 - - [07/May/2018 17:15:39] "GET /signup HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:39] "GET /static/webcamjs_min.js HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:39] "GET /static/webcam.js HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:57] "POST /signup HTTP/1.1" 200 -
这是Python调试输出,因为您可以看到 POST 请求返回了HTTP响应代码 200 但是python中没有来自return语句的输出。
答案 0 :(得分:1)
您的代码按预期工作。您唯一错过的就是在javascript POST
函数中阅读成功的upload
请求。
function ShowCam() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
}
window.onload= ShowCam;
function snap() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="image" src="'+data_uri+'"/>';
} );
}
function upload() {
console.log("Uploading...")
var image = document.getElementById('image').src;
var form = document.getElementById('myForm');
var formData = new FormData(form);
formData.append("file", image);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/signup");
// check when state changes,
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(formData);
console.log(formData.get('file'));
console.log(formData.get('userID'));
}