I'd like to be able to display a message to the user after a download is triggered via send_from_directory.
@app.route('/downloadFile', methods=['GET'])
def download():
return send_from_directory(output_directory, "myfile.txt", as_attachment=True)
This will trigger a download after the /downloadFile endpoint is visited, but in addition to the download being triggered, I'd like to have output in the browser that says something like "file download triggered". Is there a way to achieve this? If I wasn't using send_from_directory, I could do something like this to return some JSON return {'Status': 'file download triggered'}
I'm looking for a way to combine the two, that way the user doesn't see a blank screen when they hit this endpoint.
CodePudding user response:
For any request, there can only be a single response. The HTML page response and the file download response must be their own respective responses to two separate requests.
In order to get the effect you want, you would want two endpoints: one endpoint to return an HTML response, and a second endpoint to handle the file download.
Your HTML response from your first route can contain javascript code to initiate the file download from the second endpoint. An implementation of this might look something close to pushpak ruhil's answer.
CodePudding user response:
What you could do is, return render_template() at the given endpoint to render an html file which would display something like "your file is now being downloaded" or whatever message you want and in the same html file, use a JS to trigger a 2nd endpoint which would download the file.
@app.route('/downloadPage', methods=['GET'])
def download_page():
return render_template("download_page.html")
@app.route('/downloadFile')
def download_file():
return send_from_directory(output_directory, "myfile.txt", as_attachment=True)
In the HTML file, the JS will be something like -
<SCRIPT>
window.location.href = "/DownloadFile";
</SCRIPT>