0

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.

user2480542
  • 2,345
  • 4
  • 20
  • 25

1 Answers1

3

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']
Abe Karplus
  • 7,360
  • 2
  • 23
  • 24
  • great..works beautifully. Now if you can please suggest one more thing based on your expertise: How can I send the file directly to the python method without reading it in javascript, so that it can be directly read and amended by the python method? – user2480542 Dec 01 '13 at 08:58
  • @user2480542 The Flask documentation at http://flask.pocoo.org/docs/patterns/fileuploads/ has a good explanation. Basically, instead of using Javascript you actually submit the form, where you can access the files from `request.files`. – Abe Karplus Dec 01 '13 at 09:02
  • But if i want to send the file via ajax..and let the method receive it..what would be the way? – user2480542 Dec 01 '13 at 09:10
  • 1
    @user2480542 I found this StackOverflow answer http://stackoverflow.com/questions/4856917/jquery-upload-progress-and-ajax-file-upload/4943774#4943774 with a few methods for AJAX file upload. – Abe Karplus Dec 01 '13 at 09:19