jldork jldork - 1 year ago 208
Python Question

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)
(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
object is simply a unicode string,
'[object File]'

The code

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


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

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.

Answer Source

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