如何接受在Flask中通过ajax发送的FormData?

时间:2016-10-17 16:50:56

标签: python ajax flask

我正在尝试使用Ajax POST请求在FormData中发送图像文件。 我遇到了两个问题:

  1. 我不知道如何在烧瓶部件上提取FormData
  2. 制作ajax POST请求时出现500内部服务器错误(不确定这是否是因为1)
  3. 谢谢

    Flask python代码:

    @app.route('/', methods=['GET','POST'])
    def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file: # and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(os.getcwd()+"/static", "current_image.jpg"))
            return jsonify({'tasks': tasks})
    

    HTML和Javascript代码:

    <input id="pictureInput" type=file name=file>
    <input type=submit value=Upload id="button">
    
    <script type="text/javascript">
    var pictureInput = document.getElementById("pictureInput");
    var myFormData = new FormData();
    myFormData.append('pictureFile', pictureInput.files[0]);
    
    $("#button").click(function(){
        console.log(pictureInput);
        console.log(pictureInput.files[0]);
        console.log(myFormData);
    
        $.ajax({
          url: "http://localhost:8000/",
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          dataType : 'json',
          data: myFormData,
          success : function(data){
                console.log(data);
          },
        });
    });
    </script>
    

    错误: enter image description here

2 个答案:

答案 0 :(得分:0)

以下代码应该适合您。 您需要将static文件夹与app.py文件处于同一级别

<强> app.py

import os
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)


@app.route('/', methods=['GET','POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(os.getcwd()+"/static", "current_image.jpg"))
            tasks = []
            return jsonify({'tasks': tasks})


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

上面的代码中没有定义任务,所以我只是将它初始化为一个空列表。您还需要确保在模板中加载了jQuery。

答案 1 :(得分:0)

1.我不知道如何提取flask部分的FormData

为了提取formrdata,您可以编写以下代码

@app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
    file = request.files['pictureFile'] # according to the name you append to formdata

2.发出ajax POST请求时出现500内部服务器错误(不确定这是不是因为1)

实际上,如果找不到该文件,则没有正确的响应,因此无法正常工作。

您可以参考以下示例代码

@app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
    isSuccess = False
    if 'file' not in request.files:
         return jsonify({"IsSuccess" : isSuccess, "Message": "No file part"})

    file = request.files['pictureFile'] # according to the name you append to formdata

    if file: # and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(os.getcwd(), "static", "current_image.jpg"))

        isSuccess = True
        tasks = [] 
        return jsonify({"IsSuccess" : isSuccess, "tasks": tasks})

 return jsonify({"IsSuccess" : isSuccess, "Message": "Error occurs"})