mickzer
mickzer

Reputation: 6348

File Upload in Flask - 400 Bad Request

I'm trying to do a file upload to my Flask backend via AJAX in JQuery.

My Python side looks like this:

@app.route('/upload/', methods=['POST', 'GET'])
def upload():
    if request.method == 'GET':
        return render_template('uploadfile.html')
    elif request.method == 'POST':
        file_val = request.files['file']
        return 'it worked!'

Note that it works when I do a normal submit of the form.

My HTML and AJAX looks like this:

<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
    <label for="file">Select a file</label>
    <input name="file" type="file">
</fieldset>
<fieldset>
    <button id="upload-file-btn" type="button">Upload</button>
</fieldset>

$(document).on("click", "#upload-file-btn", function() {
    var form_data = new FormData($('#input-file')[0]);
    $.ajax({
        type: 'POST',
        url: '/upload/',
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        async: false,
        success: function(data) {
            alert("UREKA!!!");
        },
       error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });

    return false;
});

However, I'm getting a 400 response when the AJAX request is performed. I'm thinking this is something to do with the contentType, but would really appreciate any guidance :)

Upvotes: 0

Views: 1999

Answers (1)

Jai
Jai

Reputation: 74738

I don't see any element with this id $('#input-file'), my guess either you want to have form's id or just input[type="file"]'s id.

You might try with this:

var form_data = new FormData($('input[type="file"]')[0]);

Upvotes: 1

Related Questions