How to accept FormData sent via ajax in Flask?
<p>I'm trying to send an image file in a FormData using an Ajax POST request.
I am faced with 2 problems:</p>

<ol>
<li>I do not know how to extract the FormData on the flask part</li>
<li>I 500 internal server error when making an ajax POST request (not sure if this is because of 1) </li>
</ol>

<p>Thank you</p>

<p>Flask python code:</p>

<pre><code>@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})
</code></pre>

<p>HTML and Javascript code:</p>

<pre><code>&lt;input id="pictureInput" type=file name=file&gt;
&lt;input type=submit value=Upload id="button"&gt;

&lt;script type="text/javascript"&gt;
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);
      },
    });
});
&lt;/script&gt;
</code></pre>

<p>Error:
<a href="https://i.stack.imgur.com/yiAgd.png" rel="nofollow"><img src="https://i.stack.imgur.com/yiAgd.png" alt="enter image description here"></a></p>

<p>The following code should work for you. <strong>You need to have the <code>static</code> folder in the same level as your <code>app.py</code> file</strong></p>

<p><strong>app.py</strong></p>

<pre><code>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)
</code></pre>

<p>tasks is not defined above in your code, so I just initialized it to an empty list. You need also to make sure that jQuery is loaded in your template.</p>

python ajax flask