I'm using flask's send_file
method to try and make the browser download a .txt file. Problem is the browser does not download anything.
Here's my python function:
@app.route('/download_zip', methods=['POST'])
def download_zip():
file_name = 'test.txt'
return flask.send_file(file_name, as_attachment=True, mimetype='text/plain')
Here's my jQuery function that triggers the POST request:
function batchDownload() {
$.post('/download_zip', {
file_name: 'temp.zip'
}).done(function(data) {
alert(data);
}).fail(function() {
alert('Error. Could not download files :(');
});
}
Funny thing is the alert(data)
in the .done(...)
callback displays the file's content to the browser. So the browser is receiving the file content but just not downloading it.
Any ideas?
Thanks in advance!
EDIT
Added a form to the page:
<form id="download"></form>
And added this to the .done(...)
callback:
$form = $('#download');
$form.submit();
I'm guessing I need to somehow link the data (file) returned by the server response to the POST request?
This is not a flask related question. It's how browsers and javascript works.
You're downloading the file in Ajax so the result is passed to your Ajax callback.
You want instead to make the browser download data in his usual way.
To do so you must use a form
and call the .submit()
method on it.
Just create the form
in the page with hidden fields and submit it in the javascript function. It should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With