Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask server cannot read file uploaded by POST request

I have my React client post a file with the fetch api to the '/dataset' endpoint.

import 'whatwg-fetch';

uploadData(csv) {
    this.dataset = csv;

    fetch('/dataset', {
        method: 'POST',
        body: this._fileToFormData(csv)
    }).then(
        (response) => {
            console.log(response);
        }
    ).catch( () => {} );
};

_fileToFormData(file) {
        var formData = new FormData();
        formData.append('file', file);
        return formData
    };

My Flask server is supposed to pick it up.

@app.route('/dataset', methods=['POST'])
def dataset():
    print request.get_data()
    csv_data = request.form['file']
    print csv_data
    return '{ "fake_json":100}', 200

However, the csv_data object is simply a unicode string, '[object File]'

The code

print "form:", request.form
print "files:", request.files

returns

ImmutableMultiDict([('file', u'[object File]')])
ImmutableMultiDict([])

How do I get the actual contents of the CSV file?

=== EDIT: Solved ===

the variable csv was actually a single file array, so I needed to extract the file out.

like image 856
jldork Avatar asked Jun 18 '16 18:06

jldork


1 Answers

Uploaded files are available in request.files, not request.form. The values are file-like objects, so to get the data you need to read the file.

data = request.files['file'].read()

See the Flask docs for some examples on working with uploads.


You also need to upload the file correctly. GitHub's fetch polyfill has an example using FormData to format the body properly. You must pass a single file or input to each call to append.

var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])

fetch('/dataset', {
  method: 'POST',
  body: data
})
like image 66
davidism Avatar answered Oct 18 '22 16:10

davidism