1

I am trying to read-in a file from a Python request, form data. All I want to do is read-in the incoming file in the request body, parse the contents and return the contents as a json body. I see many examples out there like: if 'filename' in request.files:, however this never works for me. I know that the file does in fact live within the ImmutableMultiDict type. Here is my working code example:

if 'my_file.xls' in request.files:
    # do something

else:
    # return error
Andrew Ray
  • 186
  • 1
  • 7
  • `ImmutableMultiDict([('', )])` this is what the incoming request body contains – Andrew Ray Nov 22 '19 at 17:51
  • can you add all the code needed to make your program run? – Josh Harold Nov 22 '19 at 17:52
  • `from flask import request, Response` `from create_app import my_app` `import json` `@my_app.route('/api-examples/file_parser')` `def get_file():` ` if 'my_file.xls' in request.files:` ` # do something` ` else:` ` # return error` `# main section` `if __name__ == '__main__':` ` my_app.run(host='0.0.0.0', port=5000)` – Andrew Ray Nov 22 '19 at 17:53

1 Answers1

3
if 'file' in request.files:

This is looking for the field name 'file' which corresponds to the name attribute you set in the form:

  <input type='file' name='file'>

You then need to do something like this to assign the FileStorage object to the variable mem:

mem = request.files['file']

See my recent answer for more details of how and why.

You can then access the filename itself with:

mem.filename # should give back 'my_file.xls' 

To actually read the stream data:

mem.read()

The official flask docs have further info on this, and how to save to disk with secure_filename() etc. Probably worth a read.

All I want to do is read-in the incoming file in the request body, parse the contents and return the contents as a json body.

If you actually want to read the contents of that Excel file, then you'll need to use a library which has compatibility for this such as xlrd. this answer demonstrates how to open a workbook, passing it as a stream. Note that they have used fileobj as the variable name, instead of mem.

v25
  • 7,096
  • 2
  • 20
  • 36