Python 官方文档:入门教程 => 点击学习
目录flask接收前端ajax传来的表单Flask利用ajax进行表单请求和响应总结Flask接收前端ajax传来的表单 html,包含一个text类型文本框和file类型上传文件
html,包含一个text类型文本框和file类型上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta Http-equiv="X-UA-Compatible" content="ie=edge">
<title>拍照</title>
</head>
<body>
<h1>拍照上传演示</h1>
<fORM id="upForm" enctype="multipart/form-data" method="POST">
<p>
<span>用户名:</span>
<input type="text" name="username" />
</p>
<input name="pic" type="file" accept="image/*" capture="camera" />
<a onclick="upload()">上传</a>
</form>
<img id="image" width="300" height="200" />
</body>
<script src="https://cdn.bootCSS.com/Jquery/3.4.1/jquery.min.js"></script>
<script>
function upload() {
var data = new FormData($("#upForm")[0]); //注意jQuery选择出来的结果是个数组,需要加上[0]获取
$.ajax({
url: '/do',
method: 'POST',
data: data,
processData: false,
contentType: false,
cache: false,
success: function (ret) {
console.log(ret)
}
})
//return false //表单直接调用的话应该返回false防止二次提交,<form οnsubmit="return upload()">
}
</script>
</html>
import os
from flask import Flask, render_template, request, JSONify
from werkzeug import secure_filename
TEMPLATES_AUTO_RELOAD = True
app = Flask(__name__)
app.config.from_object(__name__)
# 设置Flask jsonify返回中文不转码
app.config['JSON_AS_ASCII'] = False
PIC_FOLDER = os.path.join(app.root_path, 'upload_pic')
@app.route('/', methods=['GET'])
def hello():
return render_template('index.html')
@app.route('/do', methods=['POST'])
def do():
data = request.form
file = request.files['pic']
result = {'username': data['username']}
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(PIC_FOLDER, filename))
result['pic'] = filename
return jsonify(result)
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=8000)
前端html代码
<form id="demo_form">
输入框: <input type="text" name="nick_name" />
<input type="submit" value="ajax请求"/>
</form>
js代码
//首先需要禁止form表单的action自动提交
$("#demo_form").submit(function(e){
e.preventDefault();
$.ajax({
url:"/demo",
type:'POST',
data: $(this).serialize(), // 这个序列化传递很重要
headers:{
"X-CSRF-Token": getCookie('csrf_token')
},
success:function (resp) {
// window.location.href = "/admin/page";
if(resp.error){
console.log(resp.errmsg);
}
}
})
});
@app.route("/demo", methods=["POST"])
def demo():
nick_name = request.form.get("nick_name")
print(nick_name)
return "ok"
表单序列化很重要,否则获取的数据是None。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Flask如何接收前端ajax传来的表单(包含文件)
本文链接: https://lsjlt.com/news/176562.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0