Flask如何接收前端ajax傳來(lái)的表單(包含文件)
更新時(shí)間:2023年01月03日 16:58:16 作者:DexterLien
這篇文章主要介紹了Flask如何接收前端ajax傳來(lái)的表單(包含文件),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
Flask接收前端ajax傳來(lái)的表單
HTML,包含一個(gè)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選擇出來(lái)的結(jié)果是個(gè)數(shù)組,需要加上[0]獲取
$.ajax({
url: '/do',
method: 'POST',
data: data,
processData: false,
contentType: false,
cache: false,
success: function (ret) {
console.log(ret)
}
})
//return false //表單直接調(diào)用的話應(yīng)該返回false防止二次提交,<form οnsubmit="return upload()">
}
</script>
</html>
Python
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__)
# 設(shè)置Flask jsonify返回中文不轉(zhuǎn)碼
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)
Flask利用ajax進(jìn)行表單請(qǐng)求和響應(yīng)
前端html代碼
<form id="demo_form"> ?? ?輸入框: <input type="text" name="nick_name" /> ?? ?<input type="submit" value="ajax請(qǐng)求"/> </form>
js代碼
//首先需要禁止form表單的action自動(dòng)提交
$("#demo_form").submit(function(e){
?? ?e.preventDefault();
? ? $.ajax({
? ? ? ? url:"/demo",
? ? ? ? type:'POST',
? ? ? ? data: $(this).serialize(), ? // 這個(gè)序列化傳遞很重要
? ? ? ? headers:{
? ? ? ? ? ? "X-CSRF-Token": getCookie('csrf_token')
? ? ? ? },
? ? ? ? success:function (resp) {
? ? ? ? ? ? // window.location.href = "/admin/page";
? ? ? ? ? ? if(resp.error){
? ? ? ? ? ? ? ? console.log(resp.errmsg);
? ? ? ? ? ? }
? ? ? ? }
? ? })
});python Flask框架的代碼
@app.route("/demo", methods=["POST"])
def demo():
?? ?nick_name = request.form.get("nick_name")
?? ?print(nick_name)
?? ?return "ok"表單序列化很重要,否則獲取的數(shù)據(jù)是None。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式
這篇文章主要介紹了python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python logging模塊寫(xiě)入中文出現(xiàn)亂碼
這篇文章主要介紹了Python logging模塊寫(xiě)入中文出現(xiàn)亂碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05

