日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Flask如何接收前端ajax傳來的表單(包含文件)_python

作者:DexterLien ? 更新時間: 2023-02-09 編程語言

Flask接收前端ajax傳來的表單

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>

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__)
# 設置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)

Flask利用ajax進行表單請求和響應

前端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);
? ? ? ? ? ? }
? ? ? ? }
? ? })
});

python Flask框架的代碼

@app.route("/demo", methods=["POST"])
def demo():
?? ?nick_name = request.form.get("nick_name")
?? ?print(nick_name)
?? ?return "ok"

表單序列化很重要,否則獲取的數據是None。

總結

原文鏈接:https://lpwmm.blog.csdn.net/article/details/102871982

欄目分類
最近更新