0

I'm uploading a json file via flask, but I'm having trouble actually reading what is in the file.

# named fJson b/c of other json imports
from flask import json as fJson
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
    file = request.files['file']
    # data = fJson.load(file)
    # myfile = file.read()

I'm trying to deal with this by using the 'file' variable. I looked at http://flask.pocoo.org/docs/0.10/api/#flask.json.load, but I get the error "No JSON object could be decoded". I also looked at Read file data without saving it in Flask which recommended using file.read(), but that didn't work, returns either "None" or "".

Community
  • 1
  • 1
Joe Johnson
  • 105
  • 1
  • 2
  • 9

2 Answers2

3

Request.files

A MultiDict with files uploaded as part of a POST or PUT request. Each file is stored as FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem. http://flask.pocoo.org/docs/0.10/api/#flask.Request.files

You don't need use json, just use read(), like this:

if request.method == 'POST':
    file = request.files['file']        
    myfile = file.read()
Jair Perrut
  • 1,360
  • 13
  • 24
1

For some reason the position in the file was at the end. Doing

file.seek(0)

before doing a read or load fixes the problem.

Joe Johnson
  • 105
  • 1
  • 2
  • 9