My problem is almost exactly like in this unsolved quastion.
Downloading starts properly, if route function was called directly:
HTML
<button type="button" onclick="window.location.href='{{ url_for( 'download') }}';">
Python
@app.route('/download', methods=['GET', 'POST'])
def download():
# ...
return send_file(data,
mimetype=mimetype,
as_attachment=True,
download_name='default' + '.' + ext)
But I’d like to do some additional work on JS side.
So onclick
event triggers the function which, in its turn, tries to call flask route through ajax-request, but nothing happens. Downloading doesn’t start.
HTML
<button type="button" onclick="before_download()">
JS
async function before_download(ev) {
let name = document.getElementById('name').value;
// ...
let response = await fetch('/download', {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=utf-8'},
body: JSON.stringify({name})
});
// return await response.blob(); // Do I need this line at all?
}
Python
@app.route('/download', methods=['GET', 'POST'])
def download():
# ...
return send_file(data,
mimetype=mimetype,
as_attachment=True,
download_name=request.get_json()['name'] + '.' + ext)
What should be returned from route function? Shall I await
for it in JS?
Or maybe is there a special header for this kind of requests?
Thanks.