user2480542
user2480542

Reputation: 2945

post a file to flask url using ajax

I have a javascript method that reads the input file submitted via a form and tries to post its data to a flask url, which is supposed to read the posted data and return it with some amendments.

The HTML part:

<form id="form_1">
    <input type="file" name="file_1" id="file_1">
    <input type="submit" value="submit" id="regan">
 </form>

The JS part:

$("#form_1").submit(function(e){
    e.preventDefault(e);

    var reader = new FileReader();
    var line_data = $('#file_1').get(0);

    if (line_data.files.length) {
        var input_file = line_data.files[0];
        reader.readAsText(input_file);
        $(reader).on('load', function(e){
            data_line = e.target.result;
            $.ajax({
                    url:'url/validate/',
                    type:'POST',
                    data:{akey: data_line},
                    success:function(returned_data){console.log(returned_data);},
                    error:function(){console.log('sorry...');}
            });

        });
    }

});

The Flask/Python part:

@app.route('/validate_line/')
def validate_line_data():

    try:
        data = request.form['akey']
    except:
        data = 'bad'

    data = str(data)

    return data+'was_received'

So far, its reading the submitted text file successfully in javascript, but it seems like its not posting via the ajax post method and giving an error url/validate/ 405 (METHOD NOT ALLOWED).

Any help would be great. Thanks.

Upvotes: 0

Views: 3125

Answers (1)

Abe Karplus
Abe Karplus

Reputation: 8540

For Flask to accept POST requests, you need to specify so in the decorator:

@app.route('/validate_line/', methods=['POST'])

If you want it to accept GET requests as well, change to

['GET', 'POST']

Upvotes: 3

Related Questions