Home > Software design >  Within a Flask endpoint, how to take in a file and return a new file?
Within a Flask endpoint, how to take in a file and return a new file?

Time:07-14

I have an endpoint that takes in a csv file given by the user, the function then performs some analysis on it, and the user should then have the report downloaded onto their system.

the code looks similar to this currently:

function uploadFile(file) {
    var form = new FormData();
    form.append('file', file);
    var request = new XMLHttpRequest();
    request.open('POST', '/upload');
    request.send(form);
}
@app.route("/upload", methods=["POST"])
def endpoint_function():
    file = flask.request.files["file"]
    analysis_function(pd.read_csv(file)) # Outputs csv to 'filepath'
    return flask.send_file(filepath, as_attachment=True)

When the function is triggered from the frontend, it creates the csv, but does not download it to the users system.

I have checked that the report csv is being correctly placed at the filepath.

CodePudding user response:

I wrote a minimum working example of downloading a file from a flask route:

The directory of this app contains two files:

  • app.py - python script
  • download.txt - file to be downloaded

app.py:

# app.py
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/')
def index():
  return "<a href=\"/download\"> Download File</a>"

@app.route('/download')
def download_file():
  return send_file("download.txt", as_attachment=True)

if __name__ == '__main__':
  app.run(debug=True, port=8000, host='127.0.0.1')

Test this code on your machine, if its failing, maybe you have a setting on your browser/firewall to block file downloads.

CodePudding user response:

With the JavaScript, you'll need to await the response from the server, then you should be able to download it as would another file.

Here's a link to a post that shows you how to await the XMLHttpRequest: In JavaScript how do I/should I use async/await with XMLHttpRequest?

Hope this helps!

  • Related