0

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.

10dan
  • 1
  • 3
  • Where are you setting the filename? Is it hard coded? Have you verified in the debugger that it's value matches where analysis_function saves it's output file – barryodev Jul 13 '22 at 11:03
  • To test this, I created a csv in the root directory and tried to send_file on that. Still no download triggered. Other endpoints in the same flask app work fine, the only difference that I can think of is that this endpoint takes in a file. – 10dan Jul 13 '22 at 12:00

2 Answers2

0

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.

barryodev
  • 509
  • 3
  • 11
  • This works fine on my system, I believe the issue is with how I'm calling the endpoint in my JavaScript function. – 10dan Jul 13 '22 at 13:57
  • Well there you go, the first step in solving a problem isolating where it's occuring. You can generally do this by creating a minimum working(or breaking) example. – barryodev Jul 13 '22 at 14:00
0

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!

Samantha
  • 1
  • 2