DIRECTIONNZ
DIRECTIONNZ

Reputation: 63

POST 400 bad request when doing file upload using flask ajax call

I am trying to use Flask and jQuery to achieve file upload functionality. However, the program I am having now always returns me error on "POST 400 (bad request)".

Here is my form.html:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

    <script src="{{ url_for('static', filename='form.js') }}"></script>
</head>
<body>
<div class="container">
    <br><br><br><br>
    <form class="form-inline">
      <div class="form-group">
        <input type="file" name="file" accept=".csv" id="hc">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <br>
    <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
    <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>

Form.js:

$(document).ready(function() {

    $('form').on('submit', function(event) {

        var form_data = new FormData($('#form-inline')[0]);
        $.ajax({
            data : form_data,
            type : 'POST',
            url : '/upload',
            contentType: false,
            processData: false,
            dataType: 'json'
        })
        .done(function(data) {

            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#successAlert').hide();
            }
            else {
                $('#successAlert').text(data['name']).show();
                $('#errorAlert').hide();
            }

        });

        event.preventDefault();

    });

});

And Flask server(process.py):

from flask import Flask, render_template, request, jsonify
import os

app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route('/')
def index():
    return render_template('form.html')

@app.route('/upload', methods=['POST'])
def upload():
    target = os.path.join(APP_ROOT, "DataSource/")
    if not os.path.isdir(target):
        os.mkdir(target)

    file = request.files['file']
    if file:
        fileName = "DCData.csv"
        destination = '/'.join([target, fileName])
        file.save(destination)
        return jsonify(name=filename)

    return jsonify({'error' : 'Missing data!'})

if __name__ == '__main__':
    app.run(debug=True)

It seems that my server cannot process 'file = request.files['file']' well. Any idea how to resolve this issue?

Upvotes: 1

Views: 2640

Answers (1)

metmirr
metmirr

Reputation: 4302

mark your form tag with enctype=multipart/form-data

...
<form class="form-inline" enctype="multipart/form-data">
...

Upvotes: 1

Related Questions