0

I have a JSON string that I am reading from a web form that I would like to create a temporary file out of and allow the file to be downloaded to the local client machine. In other words my app.route reads the string, writes the string to a file and then sends the file to the client:

@app.route('/sendFile', methods=['POST'])
def sendFile():
    content = str(request.form['jsonval'])
    with open('zones.geojson', 'w') as f:
        f.write(content)
    return send_file(f)

What's the best way to make this work?

camdenl
  • 1,159
  • 4
  • 21
  • 32
  • 1
    Why do you need to write to file if it's temporary? Assuming the submit the form, and it hits your route, I think you can just print the json and set the HTTP headers to download the file instead of showing it. I think `Content-Disposition` header? – Gohn67 Oct 19 '14 at 21:13
  • 1
    Here is an example (although it uses PHP): http://stackoverflow.com/questions/11545661/php-force-download-json – Gohn67 Oct 19 '14 at 21:17
  • Indeed you can, thanks for getting me on the right track. – camdenl Oct 19 '14 at 21:32

1 Answers1

2

From this answer all that is needed is to specify the correct Response header:

From flask import Response

@app.route('/sendFile', methods=['POST'])
def sendFile():
    content = str(request.form['jsonval'])
    return Response(content, 
            mimetype='application/json',
            headers={'Content-Disposition':'attachment;filename=zones.geojson'})
oberbaum
  • 2,451
  • 7
  • 36
  • 52
camdenl
  • 1,159
  • 4
  • 21
  • 32